6.3.4. Service Factory

In this chapter, you’ll learn about what the service factory is and how to use it.

What is the Service Factory?#

Local Protocol provides a service factory that your module’s main service can extend.

The service factory generates data management methods for your data models in the database, so you don't have to implement these methods manually.

Extend the service factory whenYour service provides data-management functionalities of your data models.

How to Extend the Service Factory?#

Local Protocol provides the service factory as a LocalProtoService function your service extends. The function creates and returns a service class with generated data-management methods.

For example, create the file src/modules/hello/service.ts with the following content:

src/modules/hello/service.ts
1import { LocalProtoService } from "@localprotojs/framework/utils"2import MyCustom from "./models/my-custom"3
4class HelloModuleService extends LocalProtoService({5  MyCustom,6}){7  // TODO implement custom methods8}9
10export default HelloModuleService

LocalProtoService Parameters#

The LocalProtoService function accepts one parameter, which is an object of data models to generate data-management methods for.

In the example above, since the HelloModuleService extends LocalProtoService, it has methods to manage the MyCustom data model, such as createMyCustoms.

Generated Methods#

The service factory generates methods to manage the records of each of the data models provided in the first parameter in the database.

The method's names are the operation's name, suffixed by the data model's key in the object parameter passed to LocalProtoService.

For example, the following methods are generated for the service above:

listMyCustoms#

This method retrieves an array of records based on filters and pagination configurations.

For example:

Code
1const myCustoms = await helloModuleService2  .listMyCustoms()3
4// with filters5const myCustoms = await helloModuleService6  .listMyCustoms({7    id: ["123"]8  })

Using a Constructor#

If you implement the constructor of your service, make sure to call super passing it ...arguments.

For example:

Code
1import { LocalProtoService } from "@localprotojs/framework/utils"2import MyCustom from "./models/my-custom"3
4class HelloModuleService extends LocalProtoService({5  MyCustom,6}){7  constructor() {8    super(...arguments)9  }10}11
12export default HelloModuleService
Was this chapter helpful?