mirror of
https://github.com/directus/directus.git
synced 2026-02-13 05:45:26 -05:00
1.3 KiB
1.3 KiB
Creating a Custom API Endpoint
Custom endpoints are dynamically loaded from your configured extensions folder.
Custom endpoints are registered using a registration function:
// extensions/endpoints/my-endpoint/index.js
module.exports = function registerEndpoint(router) {
router.get('/', (req, res) => res.send('Hello, World!'));
}
The registerEndpoint function receives two parameters: router and context. Router is an express Router
instance that's scoped to /custom/<extension-name>. context holds the following properties:
services— All API interal servicesexceptions— API exception objects that can be used to throw "proper" errorsdatabase— Knex instance that's connected to the current DBenv— Parsed environment variables
Full example:
// extensions/endpoints/recipes/index.js
module.exports = function registerEndpoint(router, { services, exceptions }) {
const { ItemsService } = services;
const { ServiceUnavailableException } = exceptions;
const recipeService = new ItemsService('recipes');
router.get('/', (req, res) => {
recipeService
.readByQuery({ sort: 'name', fields: '*' })
.then(results => res.json(results))
.catch(error => { throw new ServiceUnavailableException(error.message) });
});
}