Skip to content

Instantly share code, notes, and snippets.

@Fusseldieb
Last active April 6, 2022 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fusseldieb/c7a8febf6acda689f1fdb4b3724a3f88 to your computer and use it in GitHub Desktop.
Save Fusseldieb/c7a8febf6acda689f1fdb4b3724a3f88 to your computer and use it in GitHub Desktop.
// Snippet for Directus' custom endpoint (tested on v9.8.0)
// This snippet checks if a role named "Homepage" is present and authenticates with it to execute custom logic
// In this case, it returns *all* items inside "products" where "visible_on_homepage" is set to true.
const { getPermissions } = require('directus/utils/get-permissions');
const { getSchema } = require('directus/utils/get-schema');
module.exports = function registerEndpoint(router, { services, exceptions, database }) {
router.get('/products', async (req, res, next) => {
const { ItemsService } = services;
const { ServiceUnavailableException } = exceptions;
// Searches for the role named "Homepage" and gets its UUID for the accountability authentication
// This is made that way to ease portability since there can be different UUIDs on dev and prod server
const role_res = await database("directus_roles").select("id").where({ name: "Homepage" });
if (role_res.length === 0) {
return next(new ServiceUnavailableException("Role doesn't exist"));
}
const accountability = {
role: role_res[0].id,
admin: false,
app: false
};
const schema = await getSchema(accountability);
accountability.permissions = await getPermissions(accountability, req.schema);
const ProductsService = new ItemsService('products', { schema, accountability: accountability });
ProductsService
.readByQuery({ fields: ['model'], filter: { visible_on_homepage: true }, limit: -1 })
.then((results) => {
res.json(results);
})
.catch((error) => {
return next(new ServiceUnavailableException(error.message));
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment