README
@egomobile/api-utils
REST API extensions for @egomobile/http-server module, a very fast alternative to Express.js
Install
Execute the following command from your project folder, where your
package.json
file is stored:
npm install --save @egomobile/api-utils
Usage
Quick example
Build API responses
import createServer, { query, params } from "@egomobile/http-server";
import { apiResponse, parseListQuery } from "@egomobile/api-utils";
const app = createServer();
app.get("/users", [query(), parseListQuery()], async (request, response) => {
// load all users into 'allUsers'
// use request.listQuery, created by middleware of parseListQuery(),
// to select items inside data source of 'allUsers'
// and save it to 'selectedUsers'
apiResponse(request, response)
.withList({
limit: request.listQuery!.limit,
offset: request.listQuery!.offset,
totalCount: allUsers.length,
items: selectedUsers,
}) // set list for 'data' prop
.send(); // write all data to client
});
app.get(params("/users/:id"), async (request, response) => {
// load user with :id into 'user'
apiResponse(request, response)
.withData(user) // set value for 'data' prop
.addMessage({
type: "info",
message: "foo",
}) // an info message for the user
.addMessage({
type: "warn",
message: "bar",
internal: true,
}) // a warning message for internal usage
.send(); // write all data to client
});
app.listen().catch(console.error);
Error handling
import createServer from "@egomobile/http-server";
import { handleApiError, handleApiNotFound } from "@egomobile/api-utils";
const app = createServer();
// set error handlers
app.setErrorHandler(handleApiError());
app.setNotFoundHandler(handleApiNotFound());
// ...
app.listen().catch(console.error);
Credits
The module makes use of:
- joi by Sideway Inc.
Documentation
The API documentation can be found here.