Restful web services (/wsapi)
Check out Profound API. It offers all of these features plus many more.
Overview
Creating RESTful web services is enabled through the creation of the file/table DbDefn module.
The web service routes are automatically prefixed with /wsapi:
Profound.js - A get list would look like
http://server/wsapi/customers.
Built-In CRUD Routes
Here is an example of a file or table called order_line that is on a MySQL database and uses all of the built-in REST services.
Table of Contents
order_line.DbDefn.js
// order_line.DbDefn.js
// Describes the order_line table (here on MySQL) and turns on the built-in
// CRUD web services. Each key under "routes" is a built-in function name;
// the value is the URL path, which is automatically prefixed with /wsapi.
module.exports = {
useSQL: true,
dbObject: "order_line",
uniqueKey: [
{ field: "order_id", ascending: true },
{ field: "line_id", ascending: true }
],
routes: {
add: "/orderdetails", // POST /wsapi/orderdetails
get: "/orderdetails/:order/:line", // GET /wsapi/orderdetails/1001/2
getList: "/orderdetails/:order", // GET /wsapi/orderdetails/1001
update: "/orderdetails/:order/:line", // PUT /wsapi/orderdetails/1001/2
delete: "/orderdetails/:order/:line" // DELETE /wsapi/orderdetails/1001/2
}
}You do not need to have anything in this module file unless you are using a database other than IBM i and you will also use the built-in CRUD methods: get, getList, add, update, and delete.
The only thing that was altered was the addition of the routes section. The routes above are all of the standard built-in functions:
add - Uses the
POSTmethod.get and getList - Use the
GETmethod.update - Uses the
PUTmethod.delete - Uses the
DELETEmethod.
If add and update were not included, no web service would exist for them. Any of these can be overridden by defining the route differently (see below).
Overriding a Built-In Route
Here is a complete example of that same order_line file or table, but with the built-in add function overridden, and with a custom find function that can be used as a web service or by any Profound.js module, because the function is exported.
order_line.DbDefn.js
function customAdd(request, response) {
pjs.defineTable("orderline", { keyed: true, add: true });
var qty = parseInt(request.body.qty) || 1;
// Make sure the QTY is >= 1
request.body.qty = qty < 1 ? 1 : qty;
var result = orderline.write(null, request.body);
response.send(result);
}
function findOne(request, response) {
pjs.defineTable("orderline", { keyed: true, read: true });
var order = request.order || request.query.order || request.params.order;
var line = request.line || request.query.line || request.params.line;
var data = orderline.getRecord(order, line);
if (response)
response.send(data);
else
return data;
}
module.exports = {
useSQL: true,
dbObject: "order_line",
uniqueKey: [
{ field: "order_id", ascending: true },
{ field: "line_id", ascending: true }
],
findOne: findOne,
routes: {
add: { path:"/orderdetails", handler: customAdd }, // notice the handler property is set to this "customAdd" function.
get: "/orderdetails/:order/:line",
findOne: { method: "get", path:"/orderdetails/find"}, // notice that handler property is not set, but the name "findOne" is an exported function, so it will auto connect them.
getList: "/orderdetails/:order",
update: "/orderdetails/:order/:line",
delete: {path: "/orderdetails/:order/:line", authorize:"apiAuthenticate.js"}, // notice the authorize property is set to a javascript file. This file is yours to create and maintain. It will be called before this action.
}
}All functions that use any of the Profound.js APIs should be declared outside of the exports section.
Make sure your function names do not match the existing RLA functions, because the RLA functions take precedence.
Defining Routes
You can define the routes in a few different ways.
name: "url path"
The route method defaults to
POST, unless it is one of the built-in functions described above.The name is also the name of the function to be called.
Here is an example of creating your own web service. The function is named changeQuantity, so the name of the route should be the same.
function changeQuantity(request, response) {
var result = null;
pjs.defineTable("orderline", { keyed: true, read: true, update: true, delete: true });
var newQty = parseInt(request.body.qty) || 0;
// If QTY is <= 0 then delete it, else update it
if (newQty <= 0)
result = orderline.delete([request.params.order, request.params.line]);
else {
var item = orderline.getRecord([request.params.order, request.params.line]);
item.qty = newQty;
result = orderline.update(null, item);
}
response.send(result);
}
module.exports = {
...
changeQuantity: changeQuantity, // This will allow this function to be available to other modules
routes: {
...
changeQuantity: "/orderdetails/:order/:line"
}
}Routes are unique based on the route method plus the path. In the example above, this route would resolve to be the same as the built-in update function. The Profound.js web service registration program only registers the first occurrence of a route; any other duplicates are logged as errors. This uniqueness rule applies across all DbDefn modules, all of them need to be unique.
There are a few very simple ways to work around this:
Change the path to be more distinct, for example
changeQuantity: "/orderdetails/:order/:line/updqty".Use the next way to define a route, which allows you to define the route method.
name: { method: "route method", path: "url path" }
Same as above, with the option to override the routing method.
function changeQuantity(request, response) {
var result = null;
pjs.defineTable("orderline", { keyed: true, read: true, update: true, delete: true });
var qty = parseInt(request.body.qty) || 0;
// If QTY is <= 0 then delete it, else update it
if (qty <= 0)
result = orderline.delete([request.params.order, request.params.line]);
else {
orderline.getRecord([request.params.order, request.params.line]);
result = orderline.update(null, request.body);
}
response.send(result);
}
module.exports = {
...
changeQuantity: changeQuantity, // This will allow this function to be available to other modules
routes: {
...
changeQuantity: { method: "patch", path: "/orderdetails/:order/:line" },
}
}name: { method: "route method", path: "url path", handler: "the function" }
Same as above, with the option to override the function to be called.
The
handlervalue should be the actual function object.Because this definition has both the function and the path, the name only needs to be unique enough to satisfy JavaScript rules.
function changeQuantity(request, response) {
var result = null;
pjs.defineTable("orderline", { keyed: true, read: true, update: true, delete: true });
var qty = parseInt(request.body.qty) || 0;
// If QTY is <= 0 then delete it, else update it
if (qty <= 0)
result = orderline.delete([request.params.order, request.params.line]);
else {
orderline.getRecord([request.params.order, request.params.line]);
result = orderline.update(null, request.body);
}
response.send(result);
}
module.exports = {
...
changeQuantity: changeQuantity, // This is only be needed if you want to expose this function to other modules
routes: {
...
updQty: {method: "patch", path: "/orderdetails/:order/:line", handler: changeQuantity }
}
}Example: Authorizing a Route
The authorize property on a route names a JavaScript file that is called before the route’s action runs. This file is yours to create and maintain.
Profound.js 5 (Fibers)
apiAuthenticate.js (Profound.js 5)
function authenticate(request, response, next) {
const Fiber = require('profoundjs-fibers');
// Do whatever is needed to authenticate/authorize the user: pjs.query, pjs.call, ...
// For example, say a request contains an API key in a header
// And you have a table that contains API keys and values for API Users
// This authentication logic might look something like this:
let filter = pjs.data.createCondition("apiKey", "=", request.headers["api-key"]);
let user = pjs.data.get("apiUsers", filter, 1);
if (!user)
throw new pjs.NotAuthorizedError();
Fiber.current.session.user = user.name;
// "next() -- is what will call your webservice
next();
}
exports.run = authenticate;Profound.js 6 and 7 (Promises)
Profound.js 6 replaced Fibers with Promises and async/await (see Promises). The version 5 example above still runs on version 6 and 7, because Profound.js rewrites require("profoundjs-fibers") at module transformation time, but new code should be written like this instead:
apiAuthenticate.js (Profound.js 6 and 7)
// Profound.js 6 and 7 (Promises).
// Fibers no longer exist, so there is no "profoundjs-fibers" require and no
// Fiber.current. Write the handler as an ordinary top-down function.
//
// The signature is unchanged from version 5: the Express request and response
// objects, plus next(), which runs the web service this route points at.
async function authenticate(request, response, next) {
// Look up the caller's API key in your own table of API users.
// pjs.data.get() returns a Promise. Module transformation would add the
// await for you, but coding it is clearer and avoids surprises.
// With a limit of 1, pjs.data.get() returns a single row object, or null.
const filter = pjs.data.createCondition("apiKey", "=", request.headers["api-key"]);
const user = await pjs.data.get("apiUsers", filter, 1);
// Throwing NotAuthorizedError makes Profound.js respond with HTTP 403.
// Any other uncaught exception results in HTTP 500.
if (!user) throw new pjs.NotAuthorizedError();
// pjs.session is session storage shared by every program call in this
// session, so the web service can read who the caller is.
pjs.session.apiUser = user.name;
// next() runs the web service. Await it -- without the await, this function
// returns before the web service has finished, which is the missing-await
// pitfall described on the Promises pages. Omit next() entirely to stop the
// request here.
await next();
}
exports.run = authenticate;