Last active
April 6, 2022 17:15
-
-
Save Fusseldieb/c7a8febf6acda689f1fdb4b3724a3f88 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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