Service
Service
Service is the "glue" for and main interaction point between user and backend. In traditional Model-View-Controller design architecture, it represents Controller.
Service provides methods for user input sanitization, whitelisting and validation. It can be bound to regular Mariner Model or to custom-tailored model. Also, by default it users Mariner Validator, but you can easily replace it with custom one.
Creating and configuring Service
To create a Service, we pass a configuration object.
Configuration Object
Only required properties are model
and name
.
Basic Service methods
In previous step, we instantiated the service, calling service methods can be done as follows:
Default Service Methods
Service provides 5 default service methods, though it can be extended or overriden.
Adding, overriding and deleting methods
To extend or override a service with your custom method, just extend the instantiated object:
Deleting (method not allowed):
Sanitization
Often, you need to prevent user from sending inappropriate parameters, so you can create a whitelist of allowed params that Service accepts. All other params will be ignored. You need to pass a Configuration object as follows methodName
: [Array of accepted fields]
.
Sanitization works also for nested structures, for example: const sanitize = { find: ['address.street'] }
will allow users to add address object, with street property.
Validation
By default, Service uses validate.js, and all validators can be used.
Replacing default validator and sanitizer
You can replace both validator and sanitizer, by passing custom functions:
Validator function accepts data
and constraints
as second argument and should return undefined
if data is valid, or to return error object with information about errors.
Sanitizer accepts data
, whitelist
and passThru
. whitelist
is an array of allowed fields. passthru
is an array of keys that should be ignored in sanitizer if using default Mariner model ($or
, $where
, etc...).
Emit function
After every successful method, emit function will be called, if provided.
Function signature has 3 arguments:
eventName
, for example, after creating an user, eventName isuser:create
payload
, data of newly created user (after creation)params
, params used to create an user (before creation)
Last updated