Automatic REST Crud
In cborm 2.5 we introduced the Base Resource Handler for ORM entities. This base handler will create a nice framework for creating a RESTFul CRUD for your entities based on ColdBox 6 Resources: https://coldbox.ortusbooks.com/the-basics/routing/routing-dsl/resourceful-routes
This means that we will create all the boilerplate code to list, show, create, update and delete your entities. Including relationships, validation, population, pagination and different ways to render (include/exclude) your data thanks to Mementifier. Get ready to start creating RESTFul services in no time!
You must be using ColdBox 6 for this feature to work

Settings

To start off with our resources support, you can start by adding the following settings to your config/Coldbox.cfc in the moduleSettings.cborm struct:
1
cborm = {
2
// Resource Settings
3
resources : {
4
// Enable the ORM Resource Event Loader
5
eventLoader : false,
6
// Prefix to use on all the registered pre/post{Entity}{Action} events
7
eventPrefix : "",
8
// Pagination max rows
9
maxRows : 25,
10
// Pagination max row limit: 0 = no limit
11
maxRowsLimit : 500
12
}
13
}
Copied!
    eventLoader : If enabled, upon application startup it will register all the following events for EVERY entity managed by Hibernate
    eventPrefix : By default if you enable the eventLoader then we will register interception points for all crud events for every entity using the pattern pre|post{Entity}{Action}. You can use this setting to prefix the events like so: {eventPrefix}pre|post{Entity}{Action}
    maxRows : By default the cborm resource handler will paginate results, you can choose your pagination window here.
    maxRowsLimit : By default it will not allow more than 500 records to be returned from the listing method. However, you can make this 0 or anything you like.

Registered Events

Once the resource event loader is activated, it will ask Hibernate for all the managed entities and register the following events in ColdBox so you can create interceptors that listen to them:
    pre{entityName}List
    post{entityName}List
    pre{entityName}Save
    post{entityName}Save
    pre{entityName}Show
    post{entityName}Show
    pre{entityName}Update
    post{entityName}Update
    pre{entityName}Delete
    post{entityName}Delete
You can use the eventPrefix setting to add a prefix to all these events.

Define Your Entities

It's time to focus on your entities now. Build out the properties, relationships, methods and make sure you add the mementifier and validation settings so our base handler can use it for validation and for data rendering:
models/Setting.cfc
1
/**
2
* Copyright since 2020 by Ortus Solutions, Corp
3
* www.ortussolutions.com
4
* ---
5
* A setting object
6
*/
7
component
8
persistent="true"
9
table="setting"{
10
11
/* *********************************************************************
12
** PROPERTIES
13
********************************************************************* */
14
15
property
16
name="settingId"
17
fieldtype="id"
18
generator="uuid"
19
ormtype="string"
20
setter="false";
21
22
property
23
name="name"
24
notnull="true"
25
unique="true"
26
length="255";
27
28
property
29
name="value"
30
notnull="true"
31
ormtype="text";
32
33
/* *********************************************************************
34
** PK + CONSTRAINTS
35
********************************************************************* */
36
37
// Validation
38
this.constraints ={
39
"name" = { required=true, size="1..255", validator="[email protected]" },
40
"value" = { required=true }
41
};
42
43
// Mementofication
44
this.memento = {
45
defaultIncludes = [ "name", "value" ]
46
};
47
48
}
Copied!
The mementifier is a critical piece as it will allow you to pass in to the rest service includes and excludes so you can decide what will be marshalled out of the service.

Register The Resource Routes

Now that you have finished your entities, you can now register the resources you will be managing. Open your config/ColdBox.cfc or your Module's router:
config/Router.cfc
1
resources( "photos" );
Copied!
This will generate all the resourceful routes as per the ColdBox Resources Routing:

Create the Handler

Now that your resources are created, create the handler that matches the resource. You can use CommandBox: coldbox create handler settings or just create the file manually. Make sure it extends our cborm resource handler: cborm.models.resources.BaseHandler
1
/**
2
* Manage settings
3
*/
4
component extends="cborm.models.resources.BaseHandler"{
5
6
// DI
7
property name="ormService" inject="SettingService";
8
9
// The default sorting order string: permission, name, data desc, etc.
10
variables.sortOrder = "name";
11
// The name of the entity this resource handler controls. Singular name please.
12
variables.entity = "Setting";
13
// The name of the method to use for save persistence on the ORM service
14
variables.saveMethod = "save";
15
// The name of the method to use for deleting entites on the ORM service
16
variables.deleteMethod = "delete";
17
18
}
Copied!

ORM Service Injection

You will inject the orm service that will be providing the operations on your RESTFul service, this can be a virtual service a concrete service.
1
// Concrete Service
2
property name="ormservice" inject="SettingService";
3
// Virtual
4
property name="ormservice" inject="entityService:Setting";
Copied!

Private Properties

You have several private properties you can set and override behavior:
    sortOrder : The default sorting order string: permission, name, data desc, etc
    entity : The name of the entity this resource handler controls. Singular name please. Used for announcing events.
    saveMethod : The name of the method to use for save persistence on the ORM service. Defaults to save()
    deleteMethod : The name of the method to use for deleting entites on the ORM service. Defaults to delete()

Generated Actions

The base resource handler will generate the following methods for you that will match the routes that you registered via the resources() method.
Action
HTTP Method
Purpose
Route
Throws
index()
GET
List resources
/{resource}
none
create()
POST
Create a resource
/{resource}
Validation
show()
GET
Get one resource
/{resource}/:id
EntityNotFound
update()
PUT/PATCH
Update a resource
/{resource}/:id
EntityNotFound, Validation
delete()
DELETE
Delete a resource
/{resource}/:id
EntityNotFound

Consistent Output

REST is all about uniformity and consistency. The output packet produced by any of the actions you create or use, will adhere to the following schema:
1
{
2
"data": "", // The output of your actions: struct, string, array, etc
3
"error": false, // If an error ocurred
4
"pagination": { // Pagination information
5
"totalPages": 1,
6
"maxRows": 25,
7
"offset": 0,
8
"page": 1,
9
"totalRecords": 5
10
},
11
"messages": [] // Info messages
12
}
Copied!

Utility Methods

We also offer you a few utility methods once you start overriding the action methods:
1
/**
2
* Calculate the starting offset for the incoming page
3
*
4
* @page The page to lookup on
5
*
6
* @return The page start offset
7
*/
8
private function getPageOffset( page = 1 )
9
10
/**
11
* Get the max number of rows to retrieve according to global settings
12
* or passed in through RC
13
*/
14
private function getMaxRows( event = getRequestContext() )
15
16
/**
17
* Coverts a value to the correct javaType for the property passed in.
18
*
19
* @propertyName The property name
20
* @value The property value
21
*/
22
private function autoCast( required propertyName, required value )
23
24
/**
25
* Get a brand new criteria builder object
26
*
27
* @useQueryCaching Activate query caching for the list operations
28
* @queryCacheRegion The query cache region to use, which defaults to criterias.{entityName}
29
* @defaultAsQuery To return results as queries or array of objects or reports, default is array as results might not match entities precisely
30
*
31
* @return cborm.models.criterion.CriteriaBuilder
32
*/
33
private function newCriteria(
34
boolean useQueryCaching = false,
35
string queryCacheRegion = "",
36
datasource
37
)
Copied!

Action Parameters

Each action can take in not only the incoming parameters that your entities require for population and saving, but also we have added a few to help you:

Index()

Parameter
Type
Default
Description
includes
string
empty
One or a list of properties you want to include in the output packet apart from the default Includes defined in your entity. Adheres to the mementifier
excludes
string
empty
One or a list of properties you want to exclude in the output packet apart from the default excludes defined in your entity. Adheres to the mementifier
ignoreDefaults
boolean
false
If true, it will ignore all default includes and excludes and ONLY use the includes and excludes you pass. Adheres to the mementifier
sortOrder
string
variables.sortOrder
The sort ordering you want to apply to the result set. Adheres to the criteria query sort() method
page
numeric
1
Pagination is included, so you can pass in the page of records you would like to visualize.

Create()

Parameter
Type
Default
Description
includes
string
empty
One or a list of properties you want to include in the output packet apart from the default Includes defined in your entity. Adheres to the mementifier
excludes
string
empty
One or a list of properties you want to exclude in the output packet apart from the default excludes defined in your entity. Adheres to the mementifier
ignoreDefaults
boolean
false
If true, it will ignore all default includes and excludes and ONLY use the includes and excludes you pass. Adheres to the mementifier

Show()

Parameter
Type
Default
Description
includes
string
empty
One or a list of properties you want to include in the output packet apart from the default Includes defined in your entity. Adheres to the mementifier
excludes
string
empty
One or a list of properties you want to exclude in the output packet apart from the default excludes defined in your entity. Adheres to the mementifier
ignoreDefaults
boolean
false
If true, it will ignore all default includes and excludes and ONLY use the includes and excludes you pass. Adheres to the mementifier
id
numeric
0
The incoming ID of the resource to show

Update()

Parameter
Type
Default
Description
includes
string
empty
One or a list of properties you want to include in the output packet apart from the default Includes defined in your entity. Adheres to the mementifier
excludes
string
empty
One or a list of properties you want to exclude in the output packet apart from the default excludes defined in your entity. Adheres to the mementifier
ignoreDefaults
boolean
false
If true, it will ignore all default includes and excludes and ONLY use the includes and excludes you pass. Adheres to the mementifier
id
numeric
0
The incoming ID of the resource to show

Delete()

Parameter
Type
Default
Description
id
numeric
0
The incoming ID of the resource to show

Overriding Actions

You can also override the actions we give you so you can spice them up as you see fit. A part from calling the super class to finalize your REST call, we have allso added some extra arguments to your base actions so you can have fine-grained control of populations, validations, querying and much more.
1
/**
2
* Display all clientNotes by creating my own criteria object
3
* GET /api/v1/clientNotes
4
*
5
* @override
6
*/
7
function index( event, rc, prc ){
8
// Criterias and Filters
9
param rc.sortOrder = "createdDate desc";
10
param rc.page = 1;
11
param rc.isActive = true;
12
param rc.clientId = "";
13
param rc.creatorId = "";
14
15
// Build up a search criteria and let the base execute it
16
arguments.criteria = newCriteria()
17
.eq( "isActive", autoCast( "isActive", rc.isActive ) )
18
.when( len( rc.clientId ), (c) => {
19
c.eq( "client.clientId", rc.clientId );
20
} )
21
.when( len( rc.creatorId ), (c) => {
22
c.eq( "creator.userId", rc.creatorId );
23
} );
24
25
super.index( argumentCollection=arguments );
26
}
27
28
/**
29
* Display all employees using my own orm service search which
30
* must return a struct of
31
* - count : The number of records
32
* - records : The array of objects
33
* GET /api/v1/employees
34
*
35
* @override
36
*/
37
function index( event, rc, prc ){
38
// Criterias and Filters
39
param rc.search = "";
40
param rc.sortOrder = "lname";
41
param rc.page = 1;
42
param rc.isActive = true;
43
param rc.hasPayroll = false;
44
param rc.managerId = "";
45
param rc.roleId = "";
46
47
// search
48
arguments.results = variables.ormService.search(
49
"searchTerm" = rc.search,
50
"sortOrder" = rc.sortOrder,
51
"isActive" = rc.isActive,
52
"hasPayroll" = rc.hasPayroll,
53
"roleId" = rc.roleId,
54
"managerId" = rc.managerId,
55
"offset" = getPageOffset( rc.page ),
56
"max" = getMaxRows()
57
);
58
59
// response
60
super.index( argumentCollection=arguments );
61
}
Copied!

index() Arguments

Parameter
Type
Default
Description
criteria
Criteria
null
You can pass your own criteria object that we will use to execute to retrieve the records
results
struct
{ count:0, records:[] }
If you pass in a results struct, then you did the search and we will just marshall the results using pagination. The struct must contain the following:
    count : The records found
    records : The array of entities

create() Arguments

Parameter
Type
Default
Description
populate
struct
{}
The arguments you want to send into the populateModel() method alongside the entity that's being created.
validate
struct
{}
The arguments you want to send into the validateOrFail() method alongside the entity that's being validated.

update() Arguments

Parameter
Type
Default
Description
populate
struct
{}
The arguments you want to send into the populateModel() method alongside the entity that's being updated.
validate
struct
{}
The arguments you want to send into the validateOrFail() method alongside the entity that's being updated.
Happy Coding!
Last modified 5mo ago