More docs to the lib/api.js

main
Zed A. Shaw 2 years ago
parent b1f443ff37
commit e9d744f30a
  1. 43
      lib/api.js

@ -209,17 +209,60 @@ import Validator from 'Validator';
*/
export const developer_admin = process.env.DANGER_ADMIN === "1";
/*
The main class you use in `api/` handlers. Primarily used like this:
```javascript
import { API } from '../lib/api.js';
export const get = async (req, res) => {
const api = new API(req, res);
}
```
It is a very thin layer over the regular Express.js request/response objects,
but it's main purpose is to return consistent errors when validation fails.
If you don't want to use this, then look at `validation_error` to see what
you need to replicate for form validation.
*/
export class API {
/*
Constructor for the `API` class. Takes the Express.js request/response
objects.
+ `req Object` -- Express.js Request object.
+ `res Object` -- Express.js Response object.
*/
constructor(req, res) {
this.req = req;
this.res = res;
}
/*
Simply returns a status and JSON data to the browser. This normalizes
the type of the response to it's always JSON. I use this with `return`
even though it doesn't matter, mostly to make sure the control flow
exits when I want. This also helps `eslint` detect when I've missed a
branch on the returns. Ultimately Express.js doesn't care about the
return so it's harmless.
+ `status number` -- The status code as an integer.
+ `data Object` -- The object to encode as JSON. Must be JSON.stringify() capable.
+ ___return___ undefined -- Whatever `res.status().json()` returns.
*/
reply(status, data) {
return this.res.status(status).json(data);
}
/*
Redirects the browser with status 301 by default. If you want a different
status then change the second parameter (which defaults to 301).
+ `url string` -- The URL to redirect the browser to.
+ `status number (301)` -- The redirect status code to use, by default 301.
*/
redirect(url, status=301) {
return this.res.redirect(status, url);
}

Loading…
Cancel
Save