Skip to content

Instantly share code, notes, and snippets.

@Fusseldieb
Last active April 25, 2022 15:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fusseldieb/b3c5fef582cd008d70ca3b6f4c2f3780 to your computer and use it in GitHub Desktop.
Save Fusseldieb/b3c5fef582cd008d70ca3b6f4c2f3780 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 an image if the role has sufficient permissions.
// It's pretty barebone, but should get you started.
const { getPermissions } = require('directus/utils/get-permissions');
const { getSchema } = require('directus/utils/get-schema');
module.exports = function registerEndpoint(router, { services, exceptions, database }) {
router.get('/images/:imageid', async (req, res, next) => {
const { AssetsService } = services;
const { ServiceUnavailableException } = exceptions;
const imageid = req.params.imageid;
// 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 service = new AssetsService({ schema: schema, accountability: accountability });
try{
const { stream, file } = await service.getAsset(imageid, { /* Transformation Options */ })
res.setHeader('Content-Type', file.type);
res.setHeader('Accept-Ranges', 'bytes');
stream.pipe(res);
} catch(err) {
return next(new ServiceUnavailableException(err.message));
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment