yeps-restify
v0.1.0
Published
YEPS Restify
Downloads
11
Maintainers
Readme
YEPS Restify
REST API request aggregate
How to install
npm i -S yeps-restify
How to use
Config
config/default.json
{
"restify": {
"restApiServerUri": "http://localhost/"
}
}
app.js
const App = require('yeps');
const error = require('yeps-error');
const logger = require('yeps-logger');
const server = require('yeps-server');
const restify = require('yeps-restify');
const app = new App();
app.all([
error({ isJSON: true }),
logger(),
]);
app.then(restify());
server.createHttpServer(app);
Custom router
app.then(async (ctx) => {
if (ctx.req.url === '/restify') {
return restify()(ctx);
}
return app.resolve();
});
With router
const Router = require('yeps-router');
const router = new Router();
router.get('/restify').then(restify());
app.then(router.resolve());
Example
app
const App = require('yeps');
const Router = require('yeps-router');
const error = require('yeps-error');
const logger = require('yeps-logger');
const server = require('yeps-server');
const restify = require('yeps-restify');
const app = new App();
const router = new Router();
app.all([
error({ isJSON: true }),
logger(),
]);
router.get('/restify').then(restify());
app.then(router.resolve());
// REST API
const users = [
{ id: 1, name: 'User 1' },
{ id: 2, name: 'User 2' },
];
const customers = [
{ id: 1, name: 'Customer 1' },
{ id: 2, name: 'Customer 2' },
];
const countries = [
{ id: 1, name: 'Country 1' },
{ id: 2, name: 'Country 2' },
];
const restRouter = new Router();
restRouter.get('/api/users').then(async (ctx) => {
ctx.res.end(JSON.stringify(users));
});
restRouter.get('/api/customers').then(async (ctx) => {
ctx.res.end(JSON.stringify(customers));
});
restRouter.get('/api/customers/:id').then(async (ctx) => {
const id = parseInt(ctx.request.params.id, 10);
const response = customers.find(customer => customer.id === id);
ctx.res.end(JSON.stringify(response));
});
restRouter.get('/api/countries').then(async (ctx) => {
ctx.res.end(JSON.stringify(countries));
});
app.then(restRouter.resolve());
server.createHttpServer(app);
Request
/restify?users=api/users&customer=api/customer/1&countries=api/countries
Response
{
"data": {
"users": [
{ "id": 1, "name": "User 1" },
{ "id": 2, "name": "User 2" }
],
"customer": {
"id": 1,
"name": "Customer 1"
},
"countries": [
{ "name": "Country 1" },
{ "name": "Country 2" }
]
}
}
With error
{
"data": {
"users": [
{ "id": 1, "name": "User 1" },
{ "id": 2, "name": "User 2" }
],
"customer": null,
"countries": [
{ "name": "Country 1" },
{ "name": "Country 2" }
]
},
"error": {
"customer": {
"message": "Not Found"
}
}
}