Generic Controller
Generic controller is a common Plumier controller with generic type signature, it take advantage of inheritance to possibly serve CRUD API based on ORM entity.
Enable Functionality#
Generic controller supported TypeORM and Mongoose (with Plumier mongoose helper) entities. Enable the generic controller by installing the TypeORMFacility or MongooseFacility on the Plumier application.
Or if you are using mongoose helper like below
Above facilities is a common facility used if you are using TypeORM or Mongoose with Plumier. In context of generic controller above facilities will normalize entities to make it ready used by generic controller helpers.
Mark Entity Handled by Generic Controller#
After installing facility above you need to mark specific entity that will be generated into CRUD API with @genericController() like below:
Or if you using Mongoose helper
Above code will generate six routes handled by generic controller implementation.
| Method | Route | Description |
|---|---|---|
| POST | /users | Add new user |
| GET | /users/:id?select | Get user by ID |
| PUT | /users/:id | Replace user by ID (required validation used) |
| PATCH | /users/:id | Modify user by ID (required validation ignored) |
| DELETE | /users/:id | Delete user by ID |
| GET | /users | Get list of users with pagination, order, filter and projection |
Its possible to create a generic controller using generic controller factory instead of using decorator, below code will result the same.
The factory receive controller builder factory configuration like below
Getting and Saving Simple Relation#
Relational data with single value (one to one or many to one) by default will be populated on each request. For example if we have entity below:
Above code generates 6 routes for each /address and /users. User entity contains relation property to Address entity which is a one to one relation. Issuing GET /users/:id will automatically populate the address, thus the response will be like below
While GET /users/:id returns the full address object, saving address (POST, PUT, PATCH) only require the ID of the address like below
Getting and Saving Array Relation#
For array relation (one to many relation), Plumier provide a nested route to easily perform CRUD operation on child relation.
Above code showing that we apply @genericController() on the User.emails relation. Using this setup will make Plumier generate a nested routes like below
| Method | Route | Description |
|---|---|---|
| POST | /users/:pid/emails | Add new user's email |
| GET | /users/:pid/emails/:id?select | Get user's email by ID |
| PUT | /users/:pid/emails/:id | Replace user's email by ID |
| PATCH | /users/:pid/emails/:id | Modify user's email by ID |
| DELETE | /users/:pid/emails/:id | Delete user's email by ID |
| GET | /users/:pid/emails | Get list of user's emails with paging, filter, order and projection |
Its possible to create a nested generic controller using generic controller factory, below code will result the same.
Its also possible to use many to one relation to generate nested routes, from previous example we can decorate the Email.user property. This feature useful to create nested routes without explicit relation between parent-children, for example to reduce number of relation properties on parent entity.
Instead of using one to many relation, we can decorate the Email.user property and ignore User.animals property.
The generic controller factory for above feature also work the same as before, we specify tuple relation Animal and user as the parameter of the generic controller factory
Inverse Property Population#
If you are defined your one to many relation ORM configuration with inverse property, Generic controller will taking care of populating its value automatically. For example if you have ORM configuration like below.
Or if you are using mongoose helper like below
You're defined inverse property user on the one to many relation, it help Plumier to understand which property will automatically populated. So adding new email using POST /users/{pid}/emails will make user automatically populated with pid value, without having to provided on request body.
Apply Multiple Decorators#
Its possible to apply multiple @genericController() decorator on entity or entity relation, but the generated route must be unique or the route generator static check will shows errors.
Above will generates 12 routes like below
| Method | Route | Description |
|---|---|---|
| POST | /emails | Add new email |
| GET | /emails/:id?select | Get email by ID |
| PUT | /emails/:id | Replace email by ID (required validation used) |
| PATCH | /emails/:id | Modify email by ID (required validation ignored) |
| DELETE | /emails/:id | Delete email by ID |
| GET | /emails | Get list of emails with pagination, order, filter and projection |
| POST | /user-emails | Add new email |
| GET | /user-emails/:id?select | Get email by ID |
| PUT | /user-emails/:id | Replace email by ID (required validation used) |
| PATCH | /user-emails/:id | Modify email by ID (required validation ignored) |
| DELETE | /user-emails/:id | Delete email by ID |
| GET | /user-emails | Get list of emails with pagination, order, filter and projection |
Filters#
Generic controller provided filter query string to narrow API response. The query respects the @authorize.read() and @authorize.writeonly(). Its mean you will not able to query
Using above code enabled us to query the response result using syntax string like below
Several filter supported based on property data type, for more information see the Query Language Specification
Delete Column#
By default when you perform DELETE /users/{id} it will delete the user record permanently from the database, You can specify the delete flag by providing @entity.deleteColumn() decorator above the flag property with boolean datatype like below.
Using above code when you request DELETE /users/{id} Plumier will set the deleted property into true automatically.
Query Strings#
Both get by id and get list route has some extra query string to manipulate the response match your need.
| Query String | Example | Default | Description |
|---|---|---|---|
select | GET /users?select=name,email,dob | All properties | Select properties to include in JSON response |
limit | GET /users?limit=20 | 50 | Limit number of records returned in response |
offset | GET /users?offset=3 | 0 | Offset of the record set returned in response |
filter | GET /users?filter=(name='john' and active=true) | - | Find records by property using exact comparison |
order | GET /users?order=-createdAt,name | - | Order by properties, - for descending order |
Above query string supported by generic controller and nested generic controller.
Get By ID#
Get by ID for generic controller and nested generic controller supported select query string like below
Get List#
Get list supported all the query string, it can be combined in single request
Custom Path Name#
Plumier provide a default route path name based on entity name (pluralized), you can specify a new path name by provide it on the @genericController() parameter.
Above code showing that we specify custom path name user-data/:uid, it will generate routes like below
| Method | Route | Description |
|---|---|---|
| POST | /user-data | Add new user |
| GET | /user-data/:uid | Get user by ID |
| PUT | /user-data/:uid | Replace user by ID (required validation used) |
| PATCH | /user-data/:uid | Modify user by ID (required validation ignored) |
| DELETE | /user-data/:uid | Delete user by ID |
| GET | /user-data | Get list of users with paging, filter, order and projection |
For nested generic controller you need to specify ID for parent and the child
Above code will generate routes below
| Method | Route | Description |
|---|---|---|
| POST | /user-data/:uid/email-data | Add new user's email |
| GET | /user-data/:uid/email-data/:eid | Get user's email by ID |
| PUT | /user-data/:uid/email-data/:eid | Replace user's email by ID |
| PATCH | /user-data/:uid/email-data/:eid | Modify user's email by ID |
| DELETE | /user-data/:uid/email-data/:eid | Delete user's email by ID |
| GET | /user-data/:uid/email-data | Get list of user's email with paging, filter, order and projection |
Control Access To The Entity Properties#
Plumier provide functionality to protect your data easily, you can use @authorize decorator to authorize user to write or read your entity property.
info
Refer to Security on how to setup user authorization on your Plumier application
Above code showing that we apply @authorize decorator on password and role property which contains sensitive data. Using above configuration password will not be visible on any response, and role only can be set by SuperAdmin and Admin. Below list of authorization you can use to protect property of the entity
| Decorator | Description |
|---|---|
@authorize.route("SuperAdmin") | Protect route can be accessed by specific role (SuperAdmin) |
@authorize.write("SuperAdmin") | Protect property only can be write by specific role (SuperAdmin) |
@authorize.read("SuperAdmin") | Protect property only can be read by specific role (SuperAdmin) |
@authorize.readonly() | Protect property only can be read and no other role can write it |
@authorize.writeonly() | Protect property only can be write and no other role can read it |
Control Access To The Generated Routes#
You can specify authorization into specific generated route by providing more configuration on the @genericController() decorator.
Above code showing that we apply authorization to the mutators() http methods. mutators() is a syntax sugar to specify generic controller actions handled the POST, PUT, PATCH and DELETE. Using above configuration the result of the generated routes are like below
| Action | Method | Route | Access |
|---|---|---|---|
save | POST | /users | SuperAdmin, Admin |
get | GET | /users/:id | Any user |
replace | PUT | /users/:id | SuperAdmin, Admin |
modify | PATCH | /users/:id | SuperAdmin, Admin |
delete | DELETE | /users/:id | SuperAdmin, Admin |
list | GET | /users | Any user |
info
If no authorization specified, the default authorization for generated route is Authenticated means all authenticated user can access the route.
For nested routes (one to many relation) you can define the same configuration like above.
Using above configuration the route access now is like below
| Action | Method | Route | Access |
|---|---|---|---|
save | POST | /users/:pid/emails | SuperAdmin, Admin |
get | GET | /users/:pid/emails/:id | Any user |
replace | PUT | /users/:pid/emails/:id | SuperAdmin, Admin |
modify | PATCH | /users/:pid/emails/:id | SuperAdmin, Admin |
delete | DELETE | /users/:pid/emails/:id | SuperAdmin, Admin |
list | GET | /users/:pid/emails | Any user |
Ignore Some Routes#
In some case you may want to hide specific route generated. You can use the ignore() configuration to ignore specific methods
Above code showing that we specify the method one by one instead of using mutators() like the previous example. The result of the
| Action | Method | Route |
|---|---|---|
save | POST | /users |
get | GET | /users/:id |
list | GET | /users |
It also can be applied on the entity relation (one to many) to ignore some nested routes like below
Above code showing that we applied the ignore decorator on the entity relation, it will produce
| Action | Method | Route |
|---|---|---|
save | POST | /users/:pid/emails |
get | GET | /users/:pid/emails/:id |
list | GET | /users/:pid/emails |
Transform Response#
Its possible to transform the response result of the GET method using transformer() configuration. For example we have entities below
You may want the response of GET /users only contains properties id, message, userName and userPicture, which userName and userPicture can be retrieved from user property.
First you need to create the model of the transformed entity.
Then specify the transformation function using transformer configuration
Above code showing that we specify the transformer configuration, the first parameter is the target model then the second parameter is the transformation function.
caution
When using response transform, the select query may still applied but the response will be based on what you returned in transform function.
Custom Query#
Unlike transform response, with custom query you provide a custom database query for getOne and/or getMany method to get different response result than the default generic controller query provided.
Using above code you provide a custom query that will be used by the GET /users/:id. To override query of GET /users you can use the getMany() method instead of getOne().
Signature of the custom query method is like below
custom(responseType, queryCallback)
responseTypeis the model used to generate schema of the response. This model used by Open API generator to generate response schema, and also used by response authorization. Important to note that the@authorize.read()on the entity will not take effect if you use different model than the entity, you need to decorate the appropriate property accordingly.queryCallbackis a function returned the database query, signature of the query callback is mostly the same forgetOne()andgetMany(), except the first parameter object, see below.
Query callback signature for getOne() and getMany() is like below
(param, ctx) => any
paramcontains the action parameter such asid,limit,offsetetc. The parameter is differ betweengetOne()andgetMany().ctxis the request context
Entity Authorization Policy#
Entity Authorization Policy (Entity Policy) is a custom auth policy designed to secure entity data by ID.
Entity policy requires unique combination between policy name and the entity type, the definition is like below.
ENTITY_CLASSis the entity which authorization policy registered to.POLICY_NAMEis the policy name, policy name may the same with other entity but must be unique when combined with entity class.- Authorization callback is where you put the authorization logic, return
trueorPromise<true>to allow otherwisefalseto restrict.
Since the internal process of entity policy is quite complex, its a lot easier to understand entity policy from its implementation. For example we created an entity policy named ResourceOwner which means the current data is owned by the login user. Then its easy to understand that for entity User, the logic of ResourceOwner is when the provided ID by authorization callback is the same as the current login user ID like below.
This policy then can be applied on the generic controller configuration builder, to secure specific route like below.
By using above configuration only the ResourceOwner of the User entity allowed to access DELETE /users/{id} route. By giving DELETE /users/12345 only user with user ID 12345 allowed to access it.
The policy also can be used to secure property using @authorize.read() or @authorize.write() like below.
Above configuration will make email filed only visible (in response body) by the owner of user, this behavior applied when the User entity used as child property.
Entity Policy Restriction#
Since entity policy designed to secure resources by ID, its important to note that route authorization (defined with @authorize.route() or ActionBuilder.authorize()) and parameter authorization (@authorize.write()) only works on route with entity ID specified.
| Route | Description |
|---|---|
POST /users | Not allowed, since no ID specified |
DELETE /users/{id} | Allowed, Callback called with ID of User entity |
POST /users/{id}/logs | Allowed, Callback called with ID of User entity |
DELETE /users/{id}/logs/{logId} | Allowed, Callback called with ID of Log entity |
Important to note that response authorization (@authorize.read()) has no restriction, its mean it will always work on all routes.
Request Hook#
Request hook enables entity to have a method contains piece of code that will be executed during request. Request hook has some simple rule
- It executed before or after the entity saved into the database, use decorator
@preSave()and@postSave() - It will be executed only on request with http method
POST,PUT,PATCH. By default it will execute on those three http methods except specified on the parameter. - It can be specified multiple request hooks on single entity
- It can have parameter with parameter binding
- It possible to bind ActionResult (execution result of the controller) on request hook
@postSave()
Above code will hash password before the entity saved into the database. Request hook has parameter binding feature, you can @bind any request part into the hook parameter, it works exactly like common Parameter Binding which also support name binding, model binding and decorator binding.
info
The ID of the current entity only accessible on @postSave using this.id, since on @postSave() the entity is not saved yet to database.
caution
Keep in mind that entity used for @preSave() and @postSave() is different, means if you using state variable to share between @preSave() and @postSave() its may not working like expected.
Its possible to specify in which http method should the hook executed by specify http method on the request hook parameter
Use Custom Generic Controller#
When the default generic controller doesn't match your need, you can provide your own custom generic controllers. For example the default generic controller for GET method doesn't contains count of the match records usually used for table pagination on UI side. You can override this function by provide a new generic controller inherited from your ORM/ODM helper:
| Generic Controller | Package | Description |
|---|---|---|
TypeORMControllerGeneric<T, TID> | @plumier/typeorm | TypeORM generic controller implementation |
TypeORMNestedControllerGeneric<P, T, PID, TID> | @plumier/typeorm | TypeORM One To Many generic controller implementation |
MongooseControllerGeneric<T, TID> | @plumier/mongoose | Mongoose generic controller implementation |
MongooseNestedControllerGeneric<P, T, PID, TID> | @plumier/mongoose | Mongoose One To Many generic controller implementation |
First define the model represent the response schema returned by each controller using generic type like below
Then create a new generic controller for both based on any of above generic controller like below
Using above code, we simply call the super.list method and use the repository count method to create the response match the Response data structure.
Note that we define the return type of the method as @type(Response, "T"), this means we specify that the Response.data property is of type of T of the generic controller.
Next, we need to register above custom generic controller on the Plumier application like below
Keep in mind that the controller created using generic controller factory GenericController(Entity) or GenericController([Entity, "children"]) will keep using the default generic controllers, to solve the issue you can use the generic controller factory factory like below.
With above code we created a new generic controller factory which based on our custom generic controllers. Export the factory and use it anywhere on your code like usual generic controller factory.
