Override a route

Overriding a route allows you to change or completely replace a Forest Admin's route behavior.

Changing Forest Admin's behavior

To achieve this, use existing snippets of default routes and modify them according to your needs.

Here are a few examples:

Use extended search by default

/routes/companies.js
...
// Get a list of Companies - Check out our documentation for more details: https://docs.forestadmin.com/documentation/v/v4/reference-guide/routes/default-routes#get-a-list-of-records
router.get('/companies', permissionMiddlewareCreator.list(), (request, response, next) => {
const recordsGetter = new RecordsGetter(companies);
const params = request.query;
params.searchExtended = true;
recordsGetter.getAll(params)
.then(records => recordsGetter.serialize(companies))
.then(recordsSerialized => response.send(recordsSerialized))
.catch(next);
});
// Get a number of Companies - Check out our documentation for more details: https://docs.forestadmin.com/documentation/v/v4/reference-guide/routes/default-routes#get-a-number-of-records
router.get('/companies/count', permissionMiddlewareCreator.list(), (request, response, next) => {
const recordsCounter = new RecordsCounter(companies);
const params = request.query;
params.searchExtended = true;
recordsCounter.count(params)
.then(count => response.send({ count }))
.catch(next);
});
...

With this snippet, only the companies collection would use extended search by default.

Using extended search is less performant than default search. Use this wisely.

Protect a specific record

/routes/companies.js
router.delete('/companies/:recordId', permissionMiddlewareCreator.delete(), (request, response, next) => {
if (request.params.recordId === 82) {
next(new Error('This record is protected, you cannot remove it.'));
return;
}
const recordRemover = new RecordRemover(companies);
recordRemover.remove(request.params.recordId)
.then(() => response.status(204).send())
.catch(next);
});

Replacing Forest Admin's behavior

To achieve this, simply remove the next() statement of any route:

/routes/companies.js
...
// Create a Action Approval - Check out our documentation for more details: https://docs.forestadmin.com/documentation/v/v4/reference-guide/routes/default-routes#create-a-record
router.post('/companies', permissionMiddlewareCreator.create(), (req, res, next) => {
// >> Add your own logic here <<
});
...

For instance, if you have a Users collection, you might want to create your users via your own api:

routes/users.js
...
const axios = require('axios');
const { users } = require('../models');
...
router.post('/users', permissionMiddlewareCreator.create(), (request, response, next) => {
const recordCreator = new RecordCreator(users);
const data = request.body.data.attributes;
axios({
url: 'https://<your-api>/users',
method: 'post',
data: data
}).then(async (res)=>{
response.send(await recordCreator.serialize(res.data))
}).catch((err)=>{
console.log('err ==>',err);
})
});