Async / Await with DBMS module in Total.js
I have improved the DBMS module by adding a new minor feature that can enhance development and save a lot of time. I have extended the .callback()
method by supporting $
argument that solves auto error handling in Total.js Schemas, Tasks, or Controllers.
Good to know:
callback($)
returns a new Promise
with auto error handling.
For understanding
NEWSCHEMA('Customers', function(schema) {
// Output will be an error in the form: "Customer not found"
schema.addWorkflow('notfound', async function($) {
var item = await DBMS().read('tbl_customer').id('NOT_FOUND').fields('id,name').error('Customer not found').callback($);
// IMPORTANT:
// The framework won't process the code below due to an error thrown by the DBMS module
item.name = item.name.toUpperCase();
$.callback(item);
});
// Output will be a record {Object} read from DB
schema.addWorkflow('found', async function($) {
var item = await DBMS().read('tbl_customer').id('8bcq001fl41d').fields('id,name').error('Customer not found').callback($);
// OK, we have a record from DB
// now we can modify it:
item.name = item.name.toUpperCase();
$.callback(item);
});
});
Example
Routing:
ROUTE('GET /api/customers/{id}/ *Customers --> read');
Schema:
NEWSCHEMA('Customers', function(schema) {
schema.setRead(async function($) {
var db = DBMS();
var customer = await db.read('tbl_customer').id($.id).fields('id,name').error('Customer not found').callback($);
customer.orders = await db.read('tbl_customer_order').where('customerid', $.id).take(10).sort('dtcreated', true).callback($);
customer.payments = await db.read('tbl_customer_payment').where('customerid', $.id).take(10).sort('dtcreated', true).callback($);
$.callback(customer);
});
});