1

Here is sample model with image field

MyModel {
  model:string
  color:string
  mymodel_image:string  // <= here the image field 
    //is designed to be string like http://domian.com/api/images/dasfs05fsd44f,png
  ...
  }

The problem I am facing is creating(writing) this model(with imagefield) on loopback. Here are the two approach I have tried so far

  1. Uploading the image first and get imageurl as a responce then post MyModel data with this imageurl that is two http requests. This approach is not conivinet because network failure(in one of the requests) might causes full process fail.

  2. Another way is a single http request with multipart form data here is what I tried to do that upload the image with operation hook before save then continue creating MyModel

    MyModel.observe('before save',function (ctx, next) {
    //do the file  upload here and get file resource url as a result
    //some thing  like this :
         Container.upload(data,options,function (err,fileObj) {   
                File.create({
                 name: fileInfo.name,
                 type: fileInfo.type,
                 container: fileInfo.container,
                 url: CONTAINERS_URL+fileInfo.container+'/download/'+fileInfo.name
     } ...);
    
       //update tee request body and execute the next  
        //callback(creating MyModel)
        //like: req.body.mymodel_image = imageurl
             next();
    

    });

the problem with this approach is I can't access the request object inside the opration hook(because the the ctx parameter does not contain request object).

I need a suggestion about the overall process and how can I workaround models with image field.

NB: I have handled storing the metadata as mentioned in this so question.

Community
  • 1
  • 1
Zstudent
  • 13
  • 1
  • 5

1 Answers1

0

What about making a remote (custom) endpoint such as POST api/MyModel/upload

Something along the lines of :

MyModel.prototype.upload = function (ctx,options,cb) {
    if(!options) options = {};

    Container.upload(data,options,function (err,fileObj) {   
        File.create({
         name: fileInfo.name,
         type: fileInfo.type,
         container: fileInfo.container,
         url: CONTAINERS_URL+fileInfo.container+'/download/'+fileInfo.name  
      }, function(err, file) {
         //.. Create 
      });

  };

  MyModel.remoteMethod(
      'upload',
      {
          isStatic: false,
          description: 'Uploads a file',
          accepts: [
              { arg: 'ctx', type: 'object', http: { source:'context' } },
              { arg: 'options', type: 'object', http:{ source: 'query'} }
          ],
          returns: {
              arg: 'fileObject', type: 'object', root: true
          },
          http: {path: '/MyModel/upload', verb: 'post'}
      }
    );
Overdrivr
  • 6,296
  • 5
  • 44
  • 70