Giter Club home page Giter Club logo

dpd-event's Introduction

Event Resource

This custom resource type allows you to write an event that will run when the resource's route receives a GET or POST request.

Installation

In your app's root directory, type npm install dpd-event into the command line or download the source. This should create a dpd-event directory in your app's node_modules directory.

See Installing Modules for details.

Usage

The On POST event will be executed when the resource's route (or a subroute) receives a POST request, and likewise with the On GET event.

It is strongly recommended that you reserve the On GET event for operations that return a value, but don't have any side effects of modifying the database or performing some other operation.

If your resource is called /add-follower, you can trigger its POST event from dpd.js:

dpd.addfollower.post('320d6151a9aad8ce', {userId: '6d75e75d9bd9b8a6'}, function(result, error) {
    // Do something
})

And over HTTP:

POST /add-follower/320d6151a9aad8ce
Content-Type: application/json
{
    "userId": "6d75e75d9bd9b8a6"
}

Event API

In addition to the generic custom resource event API, the following functions and variables are available while scripting the Event resource:

setResult(result)

Sets the response body. The result argument can be a string or an object.

// On GET /top-score
dpd.scores.get({$limit: 1, $sort: {score: -1}}, (result) => {
    setResult(result[0]);
});

getHeader(header)

Gets a request header. header is case insensitive.

if (getHeader('x-api-key') != 'mysecretapikey') cancel(401, 'bad api key');

setHeader(header, value)

Set a response header.

setHeader('Content-Type', 'text/javascript');
setResult('typeof myCallback === "function" && myCallback("hello world")');

setStatusCode(statusCode)

Sets the response http status code.

// temporary redirect to somewhere else
setStatusCode(302);
setHeader('Location', 'https://somesite/someotherplace');

url

The URL of the request, without the resource's base URL. If the resource is called /add-follower and receives a request at /add-follower/320d6151a9aad8ce, the url value will be /320d6151a9aad8ce.

// On GET /statistics
// Get the top score
if (url === '/top-score') {
    dpd.scores.get({$limit: 1, $sort: {score: -1}}, function(result) {
    setResult(result[0]);
    });
}

parts

An array of the parts of the url, separated by /. If the resource is called /add-follower and receives a request at /add-follower/320d6151a9aad8ce/6d75e75d9bd9b8a6, the parts value will be ['320d6151a9aad8ce', '6d75e75d9bd9b8a6'].

// On POST /add-score
// Give the specified user (/add-score/:userId) 5 points
var userId = parts[0];
if (!userId) cancel("You must provide a user");

dpd.users.put({id: userId}, {score: {$inc: 5}}, function(result, err) {
    if (err) cancel(err);
});

query

The query string object.

// On GET /sum
// Return the sum of the a and b properties (/sum?a=5&b=1)

setResult(Number(query.a) + Number(query.b));

body

The body of the request.

// On POST /sum
// Return the sum of the a and b properties {a: 5, b: 1}

setResult(Number(body.a) + Number(body.b));

dpd-event's People

Contributors

andreialecu avatar cmil avatar dallonf avatar ritch avatar rithish avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dpd-event's Issues

npm install / update does not work for v0.0.3

I am using heroku to deploy an app, but this error also happens on my desktop with the most up-to-date node package manager:

   -----> Building dependencies

   Pruning any extraneous modules

   Installing node modules (package.json)

   npm ERR! Linux 3.13.0-57-generic

   npm ERR! argv "/tmp/build_b6fa16b03e2763276be8011aa6b629f5/kwantum0-langdonmills-portal-7d6c3735087df3f6649187404d2c0467e399733c/.heroku/node/bin/node" "/tmp/build_b6fa16b03e2763276be8011aa6b629f5/kwantum0-langdonmills-portal-7d6c3735087df3f6649187404d2c0467e399733c/.heroku/node/bin/npm" "install" "--unsafe-perm" "--userconfig" "/tmp/build_b6fa16b03e2763276be8011aa6b629f5/kwantum0-langdonmills-portal-7d6c3735087df3f6649187404d2c0467e399733c/.npmrc"

   npm ERR! node v0.12.7

   npm ERR! npm  v2.11.3

   npm ERR! code ETARGET



   npm ERR! notarget No compatible version found: dpd-event@'>=0.0.3 <0.0.4'

   npm ERR! notarget Valid install targets:

   npm ERR! notarget ["0.0.1","0.0.2"]

   npm ERR! notarget 

   npm ERR! notarget This is most likely not a problem with npm itself.

   npm ERR! notarget In most cases you or one of your dependencies are requesting

   npm ERR! notarget a package version that doesn't exist.

   npm ERR! notarget 

   npm ERR! notarget It was specified as a dependency of 'langdonmills'

   npm ERR! notarget 



   npm ERR! Please include the following file with any support request:

   npm ERR!     /tmp/build_b6fa16b03e2763276be8011aa6b629f5/kwantum0-langdonmills-portal-7d6c3735087df3f6649187404d2c0467e399733c/npm-debug.log

   -----> Build failed

Can't call event in async mode

I have this scenario:

  1. I've created a collection to log some data.
    When a user posts to this collection I want to call a custom dpd-event where I will call an external service asynchronously. When the external call ends I want to finish up some details in the post data.
//this is the custom dpd-event
//file resources\cloudinarysrv\post.js
var cloudinary = require('cloudinary');

var done = ctx.done          // remember this to end the response (async)
ctx.done = function () { }      // dummy function for autoresponse (sync)

cloudinary.config({
  cloud_name: 'my_cloud_name',
  api_key: 'my_key',
  api_secret: 'my_secret'
});

cloudinary.v2.uploader.upload(ctx.body.ficheiro, function (error, result) {
  if (error) {
    cancel(error.message, 401);
  }
  else {
    console.log("resposta do  cloudinary");
    console.log(JSON.stringify(result));
    setResult(result);
  }
});

As to the collection:

//this is the collection
//resources\exchange\validate.js
var self = this;

if (self.logotipo) {
    dpd.cloudinarysrv.post({ ficheiro: self.logotipo }, function (result, error) {
        if (error) {
            self.logotipo = "upload error image default...";
            self.secureLogotipo = "upload error secured image default...";
        }
        else {
            console.log(JSON.stringify(result));
            console.log("já guardou na cloud e está de volta...");
//this should be get after the external call in dpd-event finishes but the call is not being done asynchronously
            self.logotipo = result.url;
            self.secureLogotipo = result.secure_url;
        }
    });
}
else {
    self.logotipo = "imagem default...";
    self.secureLogotipo = "imagem default segura...";
}

I'm not grasping the async calls concept... can someone help?

setResult inside promise resolve is not working

setResult inside promise resolve is not working and it is returning empty object {}.

var request = require("request");

var options = { method: 'GET',
url: 'https://sandbox-quickbooks.api.intuit.com/v3/company/123145907152884/invoice/130',
headers:
{ 'postman-token': '683dc6ce-5418-635a-ecb0-e20c6f0ba215',
'cache-control': 'no-cache',
authorization: 'Bearer eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..o9XTRK1HPyGg_4LDY-cbbg.rCOMTcIUusA4CRms3-ARJNi1z2JYaNCO0YOLh9e6f1lSueLFCI5X9Zc_InPwpLBev9bCjtUP_cnBPnKlPTAYDRhbJZCO3e11_zJUEgHdBfWVHxdys3VImFoDb1hyBqxbQldQh5BcR4VzVSqakl95dZcybgh8_IWikqS4XLVViFI0VsrLnnnBZNGMXqXjT04U56XtJzrNqjZO5gIc_ZfYwOk31-o9p3o9FPbYrega6uL-jul30RBhsbxtj-Y2FBSlLGC0SKgn-a6D6xBOXmfk4-bd75tASf9pCLNzxJpxQsa6zC5anYpR4H-sRJCn3swxtDCzEoONEZFYCMVCsU--cnDIzL4360XdwwSqQozTMT4OqTRX9Us7aO0h5BKRq4bxGRgKGCqfmKrv0v40lJi4q_AtFHJFZciPgfzNVpyA0JoZkuGoRPOBtrTnmWAgvZNXOkofgSyOxaZPftlylYlDIYBAKMg0jyL5EjE3Af9k7CyuhXkVAr0UkI9NzLvKiP4MCnjl7RV-LQ1lzt2-P-vjW9bqgnFaxyWMNbHe7WycqOtfgjcgCTRQmU_6cK7tovnyAPl4MfkMVLmtj_c9ACcip_AlezA3L05GjaiHIWMOgQYrHsgMw-8W_2EOabGuYLcAR635lV6ggHM7Rf3duDZqXStyh9PLvwiHbILZTkAzUR6ezuf6yoWHtEzxlBeavk1H.zIb72zHSmn-3n2KLst9anA',
accept: 'application/json',
'user-agent': 'Intuit-qbov3-postman-collection1' },
body: '{}' };

request(options, function (error, response, body) {
if (error) throw new Error(error);

console.log(body);
setResult({"speech": "hello!!!!"})
});

On Get doesn't support /id

Like dpd collection where you can query ,
followers/2aca5c26b1d75aa6 , it will return follower data for that id.
And On Get event you can read this.id or query.id.

It is not the case in dpd-event. In On Get , I have to use a regular http query and read it this way,
http://localhost:2403/followers?id=2aca5c26b1d75aa6
and in 'On Get' event,
dpd.followers.get{'id': query.id}

Hope this is the feature and this is not clear in the document as developers could expect same or
confuse between collection 'On Get' vs dpd-even 'On Get' url patten like I did.

setResult doesn't return a file

How to return a file from Deployd?
Neither of these work.

ctx.res.setHeader('Content-Type', 'application/zip');
ctx.res.end(fs.readFileSync(filePath));
or
setResult(fs.readFileSync(filePath));

dpd is not defined

I am trying to call dpd database for my project which is running well, but also I am running one server in node js, where I want to get collections from a get event,

I am using express in my node and using router, and when a particular router is called i want to fetch data from dpd database.

I tried to follow this, but if you can provide with an example will be a great help. I am not so smart :)

Thanks in advance

me is undefined in dpd-event

i'm using dpd-event "edit-subfolder", the problem when i console.log(me) in get event its gives the current user, but not in the post event and i'm still logged in, and i'm using axios.post withCredentials:true to send the sid.
dpd --version : 2.0.2

the docs are wrong

// On GET /sum
// Return the sum of the a and b properties (/sum?a=5&b=1)

setResult(query.a + query.b);

it does not work.
I get the error
Typeerror: first argument must be a string or a buffer.

Then i add query.a+query.b and convert to string before setresult.

Regards

dpd.post inside dpd-event job does not trigger emit to client browser

Hello i´m trying to notify the user browser when a dpd-event job inserts a record in a collection.
in the web app i have this code:
dpd.lixo.on('changed',function(a){console.log(a)})

then i a dpd-event job i have the next

dpd.lixo.post({"nome": "Hello world","idade":22}).then(function(todo) {
console.log(todo);
}, function(err) {
console.log(err);
});

creates a new record in lixo collections but the on post code in lixo collection does not execute this single line:
emit("lixo:changed", "new record");
when i execute the same post code in the browser console i get the emitted message
when i use postman chrome app to do the same post request it triggers the lixo collection emit code to the browser.

Why dpd-event job does not trigger the emit action?
regards
António

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.