Start a new topic

Business Logic create new File

Is there a way to create a new file using business logic.  You see I am trying to take all the objects from a given collection and the information from all of them into a single csv file that I generate.  Is there a way to do that.  


Thank you very much this helps a lot.  I may come to you for help with other issues if thats ok with you, again thanks.  

Hi,


PFA business logic code which will do all Kinvey calls for your use case.

 

function onRequest(request, response, modules) {
  var collectionAccess = modules.collectionAccess;
  var logger = modules.logger;
  var email = modules.email;

  var context = modules.backendContext;
  var utils = modules.utils;
  var appKey = context.getAppKey();
  var masterSecret = context.getMasterSecret();
  var authString = "Basic " + utils.base64.encode(appKey + ":" + masterSecret);

  var collectionname = "collection-to-be-saved-to-csv";
  var filtersonthecollection = {};

  collectionAccess.collection(collectionname).find(filtersonthecollection,function (err, docs) {
    if (err) {
      logger.info(err);
      response.complete(err);
    } else {

      var jsondocstocsv = docs; // need to convert json to csv here
      var decidedfilename = "test.csv"; // change the filename

      // logger.info(docs.length);
      var uri = 'https://' + request.headers.host + '/blob/'+ appKey;
      var options = {
        "uri" : uri,
        "method": "POST",
        "headers" : {
          "Host": request.headers.host,
          "Content-Type": "application/json",
          "X-Kinvey-API-Version": 3,
          "Authorization": authString,
          "X-Kinvey-Content-Type": "text/csv"
        },
        "json" : {"_filename": decidedfilename,"_acl": {}}
      };
      modules.request.post(options, function(error, res, body){
        if (error) {
          logger.info(error);
          response.complete(error);
        } else {
          // logger.info(res);
          // logger.info(body);

          var newfileid = body._id;
          
          var options = {
            "uri" : body._uploadURL,
            "method": "PUT",
            "headers" : {
              "Content-Type": "text/csv",
              "Content-Length": JSON.stringify(docs).length,
            },
            "body" : JSON.stringify(docs)
          };
          modules.request.put(options, function(error, res, body){
            if (error) {
              logger.info(error);
              response.complete(error);
            } else {
              // logger.info(res);
              // logger.info(body);
              var uri = 'https://' + request.headers.host + '/blob/'+ appKey + "/" + newfileid;
              var options = {
                "uri" : uri,
                "method": "GET",
                "headers" : {
                  "Host": request.headers.host,
                  "X-Kinvey-API-Version": 3,
                  "Authorization": authString,
                }
              };
              modules.request.get(options, function(error, res, body){
                if (error) {
                  logger.info(error);
                  response.complete(error);
                } else {
                  // logger.info(res);
                  logger.info(JSON.parse(body)._downloadURL);

                  // var from = "";
                  // var to = "";
                  // var subject = "";
                  // var text_body = "";
                  // from, to, subject, text_body, reply_to, html_body, cc, bcc, callback
                  // http://devcenter.kinvey.com/rest/reference/business-logic/reference.html#email-module
                  // email.send(from, to, subject, text_body);

                  response.complete(200, "OK");
                }
              });
            }
          });
        }
      });
    }
  });
}

 


Let me know if that helps.


Regards,

Wani


1 person likes this

Minor update I still cannot get it to change the fields right the issue is that it works on the api console but not the business logic console here is what I am trying now.


var context = modules.backendContext;

var utils = modules.utils;

var appKey = context.getAppKey();

var masterSecret = context.getMasterSecret();

var uri = 'https://' + request.headers.host + '/blob/'+ appKey; // id variable

var authString = "Basic " + utils.base64.encode(appKey + ":" + masterSecret);


var requestOptions = {

  uri:uri,

  headers: {

    "Authorization":authString,

    },

  body:{ _filename: 'myFilename.png',

    mimeType:'application/octet-stream' }, 

  };

  

  var auth = modules.request.post(requestOptions,function(error, res,body){

  if (error){

    response.error(error);

  } else {

    logger.info(JSON.parse(body)._downloadURL);

    response.body = JSON.parse(body);

    response.complete(res.status);

  }

});


and I get the error


400 BAD REQUEST -- { "error": "BLRuntimeError", "description": "The Business Logic script has a runtime error. See debug message for details.", "debug": "Error: Argument error, options.body.", "stack": "Error: Argument error, options.body.\n at onRequest


I am not sure what I should be doing differently again an example would appreciate it I am very sorry for the repost before waiting for response but I wanted to give the updated situation.  Thank you in advance for all of your help.   

Ok I get the idea but I am having trouble with the exact implementation I tried the code below to post a file but I can't set any of the information I am sure that I have it set up wroug so could you give an example of working code because I am having difficulty understanding the guides


var requestOptions = {

  uri:uri, 

   _id : 'my-file-id',

    _filename : 'my-file.txt',

    "mimeType" : 'text/plain',

    size : 100,

  headers: {

    "Authorization":authString,

    }

  };

  var auth = modules.request.post(requestOptions,function(error, res, body){

  if (error){

    response.error(error);

  } else {

    logger.info(JSON.parse(body)._downloadURL);

    response.body = JSON.parse(body);

    response.complete(res.status);

  }

});


An example with creating a simple set file and posting it would be appreciated thank you.  

Hi,


You can create a custom business logic endpoint which can do this. Then, you can schedule it for weekly execution.


I would suggest following flow for the BL:

  1. Get objects from collection using collectionAccess module. E.g. http://devcenter.kinvey.com/rest/guides/business-logic#Mergingdataintwocollections
  2. Upload the data to a file in Kinvey file storage using request module and Kinvey/GCS Files API. E.g. http://devcenter.kinvey.com/rest/reference/business-logic/reference.html#request-module and http://devcenter.kinvey.com/rest/guides/files#Uploading
  3. Query the file storage and get download URL for the file using collectionAccess module.
  4. Email the URL to necessary people. E.g. http://devcenter.kinvey.com/rest/guides/business-logic#Triggeringemailnotifications


I hope this helps.


Regards,
Wani

Basically I want to schedule code that every week creates it a csv file of all objects in a single collection so that csv or a link to it can be sent in an email so another party can access it.  

Hi,


Do you want to add this new file to Kinvey file storage when the business logic is executed? Can you please give me some details about your use case?


Also, Kinvey console has an option to export all the objects in a collection to a JSON file. Is that something which might be useful for you?



Regards,

Wani

Kinvey Support

Login or Signup to post a comment