Last active
April 25, 2022 15:31
-
-
Save Fusseldieb/b3c5fef582cd008d70ca3b6f4c2f3780 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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