Created
June 7, 2022 17:38
-
-
Save rijkvanzanten/4262ded33341c219626e315dad005278 to your computer and use it in GitHub Desktop.
Validates a selected image for a fake "articles" table by mime type
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
// This example uses a "articles" collection with an "image" field that we only want to allow JPEGs in | |
module.exports = function registerHook({ filter, action }, { exceptions, services, logger }) { | |
const { InvalidPayloadException } = exceptions; | |
const { FilesService } = services; | |
//=============================================================================================== | |
// Make sure only JPEGs can be associated to the collection | |
const imageFieldValidator = async (payload, _meta, { database, schema }) => { | |
// Note how the "database" object is passed in from the filter handler to the service, this | |
// allows the service to operate against the same transaction that the current filter is using | |
const filesService = new FilesService({ schema, database }); | |
// Only execute the check if the image field was actually set/altered | |
if (payload.image) { | |
const { type } = await filesService.readOne(payload.image, { fields: ['type'] }); | |
if (type !== 'image/jpeg') { | |
// This message will be shown to the user in a dialog on save, alternatively, a | |
// FailedValidationException can be used | |
throw new InvalidPayloadException('Image has to be a JPEG'); | |
} | |
} | |
}; | |
filter('articles.items.create', imageFieldValidator); | |
filter('articles.items.update', imageFieldValidator); | |
//=============================================================================================== | |
// Prevent non-jpegs from being uploaded in the first place. | |
// | |
// This currently has to be handled "reactionary", as there's no blocking filter hook for file | |
// file uploads. The solution here will respond to a file upload, and immediately delete/undo the | |
// upload when a non-jpeg is detected. | |
action('files.upload', async ({ key, payload }, { database, schema }) => { | |
const filesService = new FilesService({ database, schema }); | |
if (payload.type !== 'image/jpeg') { | |
logger.warn('Illegal file type uploaded'); | |
await filesService.deleteOne(key); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment