Access the document in the FileProcessor#12
Conversation
|
Thanks for the PR. What problem did you encounter that led you to make these changes? |
|
Hey, I want to store files via mongoose-crate but prefix the file names or target directories by data of the model e.g. the id. I found out it is possible to add the document to the options when I attach the new file, but I think this no good practise and is not supportet by e.g. mongoose-crate-gm. model.attach('files', {path: 'path/to/some/file.pdf', doc: model}, function () {})Further there was a bug in the path function, if I returned a modified path. schema.plugin(crate, {
storage: new CrateLocalFS({
path: function(attachment) {
// error occurs
return '/some-new-path/' + path.basename(attachment.path)
}
}),
fields: {
attachments: {
array: true
}
}
});The async features are nice to set a filename e.g. in the path function by creating a hash with the content of the file like this function checksumHelper (str, algorithm, encoding) {
return crypto
.createHash(algorithm || 'md5')
.update(str, 'utf8')
.digest(encoding || 'hex')
}
schema.plugin(crate, {
storage: new CrateLocalFS({
path: function(attachment, respond) {
fs.readFile(attachment.path', function (err, data) {
if (err) {
return respond(err)
}
respond(checksum(data, 'sha1'))
})
}
}),
fields: {
attachments: {
array: true
}
}
})In addition it would solve the issue#10 Custom File Names and the issue#1 Future request use the document id in the path function of mongoose-crate-localfs. |
|
+1 for this Defining path as a function should allow a flexible way to manage file storing. Such as prefixing it with a tenant id, model id, or even customizing namings for the file name and directory. This should be merged... |
I added the mongoose document to the method call of "save" and "remove" of the FileProcessor, so you can access it and pass it to the StorageProvider.
This is a breaking change for all projects who create an own FileProcessor.
Next step is the modification of the mongoose-crate-localfs. I want to pass the the document to the
pathfunction.In addition I want to add the ability to use a function for the option
directory.Both functions (document and path) should get a optional callback function passed, to support async behavior.
Sorry for my bad english 😝