Skip to content

Instantly share code, notes, and snippets.

@pulkitsinghal
Last active September 19, 2019 22:40
Show Gist options
  • Save pulkitsinghal/37bd7894336bc374cb6c to your computer and use it in GitHub Desktop.
Save pulkitsinghal/37bd7894336bc374cb6c to your computer and use it in GitHub Desktop.
Hooks for loopback file storage: after/before uploads, downloads etc.
/**
* Want to search github for sample code?
* Use the following `search criteria` in the github.com `search box` and then select `Code` from the search results:
* container upload remote language:javascript path:/common/models
*/
module.exports = function(Container) {
Container.beforeRemote('**', function(ctx, unused, next) {
console.log('4: good');
console.log('5: ctx.methodString', ctx.methodString);
if(ctx.methodString === 'container.upload') {
console.log('7: good');
next();
} else {
next();
}
}); // works
Container.afterRemote('**', function(ctx, unused, next) {
console.log('15: good');
console.log('16: ctx.methodString', ctx.methodString);
if(ctx.methodString === 'container.upload') {
console.log('18: good');
next();
} else {
next();
}
}); // works
Container.afterRemote('upload', function(ctx, unused, next) {
console.log('www: good');
next();
}); // works
// practical example
Container.afterRemote('upload', function(ctx, unused, next) {
console.log('vvv: good');
var files = ctx.result.result.files.file;
console.log('vvv: FILE(S) UPLOADED: %j', files);
// TODO - process all items in `files` array
var item = files[0];
var stream = Container.downloadStream(item.container, item.name);
stream.pipe(process.stdout);
stream.on('end', function() { next(); });
stream.on('error', next);
}); // works
Container.beforeRemote('*.upload', function(ctx, unused, next) {
console.log('xxx: good');
next();
}); // fails
Container.beforeRemote('*.container.upload', function(ctx, unused, next) {
console.log('yyy: good');
next();
}); // fails
Container.beforeRemote('container.upload', function(ctx, unused, next) {
console.log('zzz: good');
next();
}); // fails
};
@mmaia
Copy link

mmaia commented Jul 23, 2016

nice, thanks

@rahpuser
Copy link

Is there instance hooks ? for example if I call Container.upload method manually, is there a before save called ?

@salttechno
Copy link

Hello,

First of all, thank for this code.

I am trying to change the name of the file before it is uploaded to Amazon container. How can I achieve this? How can we access file name in beforeRemote?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment