webdetta-express-api
v0.1.41
Published
...
Readme
Easy HTTP API for rapid development
...
Defining methods
An API method is defined by passing methodParams and methodFunc to the Api.Method constructor.
export const myApiMethod = Api.Method(methodParams, methodFunc)Example: my-api-methods.js:
export const myApiMethod = Api.Method({
// Here you can define any params necessary for your application.
// These params can be useful for request validation in the config.callMethod() function
requiredPermissions: []
}, async (...args) => {
console.log('myApiMethod called with args:', args);
})Configuration
...
Debugging
...
Publishing
Use the Api constructor in conjunction with app.use to publish your API.
import Api from 'webdetta-express-api';
import express from 'express';
const app = express();
app.use('/api', Api(apiMethods, apiConfig));
// apiMethods -- an object containing all api methods, nested objects are supported too
// apiConfig -- configuration objectRequest processing flow
API requests are processed in 5 pipelined steps:
request handler > parse args > init ctx > call method > send response.
1. Incoming http request is captured by express.js
Express http handler is called:
- (req, res) => { ... }
The request data is parsed:
- api method name is parsed from url path
/:method - api method arguments are extracted from request body
2. config.parseArguments(req)
This step is configurable
const args = await config.parseArguments(req)
The resulting args array is passed as arguments to the API method.
Example:
config.parseArguments = async (req) => {
if (Array.isArray(req.body)) return req.body;
throw new Error('Invalid request body', { cause: req });
};3. config.initializeContext(req)
This step is configurable
const context = await config.initializeContext(req)
The result is saved in Api.ctx() async context.
Example:
import { Auth, User } from './data-layer.js'; // your application data
config.initializeContext = async (req) => {
const ctx = {};
ctx.sessionToken = req.headers['authorization'] || req.cookies?.['authorization'] || null;
if (ctx.sessionToken) {
const session = await Auth.getSession(ctx.sessionToken);
ctx.user = session ? await User.getById(session.userId) : null;
}
ctx.permissions = ctx.user?.permissions ?? ['data:read'];
return ctx; // the result is { sessionToken, user, permissions }
};4. config.callMethod({ methodParams, methodFunc, args })
This step is configurable
The methodParams and methodFunc arguments are the same as defined in Defining methods
Note that the context is not passed as an argument, it is stored in AsyncLocalStorage and can be accessed like this:const context = Api.ctx();
After executing user-defined logic (e.g. checking methodParams), the function must call the api method and return methodFunc(...args)
If function runs successfully the return value is captured as { result }
Otherwise, the thrown error is captured as { error }
Example:
import Api from 'webdetta-express-api';
config.callMethod = ({ methodParams, methodFunc, args }) => {
const { permissions = [] } = Api.ctx();
const { requiredPermissions = [] } = methodParams ?? {};
for (const permission of requiredPermissions) {
if (!permissions.includes(permission)) {
throw new Error('401:ACCESS_DENIED');
}
}
return methodFunc(...args);
};5. config.sendResponse({ req, res, result, error })
This step is configurable
This is the final step of request processing.
Here you can define custom logic and response formatting.
For example, you can set http codes based on thrown error message.
Throwing something like new Error('401:UNAUTHORIZED') or new Error('404:NOT_FOUND'),
will actually set proper http codes (401 and 404), instead of defaulting to 500.
Example:
config.sendResponse = async ({ req: _, res, result, error }) => {
if (error) {
const code = Number(String(error.message).split(':')[0]);
res.status(code || 500).send(JSON.stringify({ error: error.message }));
return;
}
res.status(200).send(JSON.stringify(result));
};