Realization of Service Layer pattern
npm install github:Maxwell88/service-layer
or
yarn add github:Maxwell88/service-layer
// serviceLayer.js
import { ServiceLayer } from "service-layer";
const koaResolver = result => this.body = result;
const koaArgsBuilder = args => args[0];
export const new ServiceLayer(
koaResolver,
koaArgsBuilder
{
before:[
/* Your before rules for example: */
{
name: "exampleRequireRule",
type: "require",
execute: (ctx,args,serviceData) => {
/*
rule logic and return changed context to another rule
or if it last than to service
*/
return ctx
}
}
],
after: [
/* Your after rules */
]
}
});
// router.js
import Router from "koa-router";
import ServiceLayer from "./serviceLayer";
import ExampleServiceClass from "./ExampleServiceClass";
const router = new Router({ prefix: config.PREFIX });
router.post("/example", ServiceLayer.useService(ExampleServiceClass));
export default router;
// router.js
import { Service } from "service-layer";
export default class Create extends Service {
/*
there you can iniate your required and custom rules for example:
*/
static exampleRequireRule = "simple args"
static exampleCustomRule = "simple args"
async execute(ctx) {
/*
service logic
*/
let result;
return result; // return data to resolver
}
}
-
Service Layer
constructor(resolver:function, argumentBuilder: function, rules: object): ServiceLayer
useService(service: Service): Function
-
argumentBuilder
- function that have one field that is array of arguments that receives middleware of Koa/express/hapi etc. and must return changed context that would been used at future. -
resolver
- function that have one argument -result
, that argument contain a final result of service,this
of resolver is a context fromargumentsBuilder
. Rules don`t have influence at resolverthis
-
rules
- object that have two fieldbefore:array
andafter:array
with objects of rule that have 3 required fieldname
,type
,execute
:Key Type Required Note name
String
+ Name of rule, and name of static param for Service
class if type of rule nothidden
type
one of hidden
,required
orcustom
strings+ type of function behavior . hidden
- execute always, don`t use static field ofService
class,required
- execute always, static field ofService
class is required otherwiseRULE_IS_REQUIRED
exeption,custom
- execute only if static field is not emptyexecute
Function
+ Name of rule, and name of static param for Service
class
-
-
Service
Service class for inheritance with required
execute: function
field (look usage). -
Exeption
constructor(data: object): Error
The data object has the following fields:Key Type Required Note fields
object
with string fields or empty+ Errored fields code
String
+ Exeption code
Licensed under the MIT license.