Exemplo n.º 1
0
  middleware() {
    let self = this;
    
    return resource({
      id: 'webhook',

      index({ query }, res) {
        if (query['hub.verify_token'] === self.verify_token) {
          res.send(query['hub.challenge']);
        }
        res.send('Error, wrong validation token');
      },
      
      create({ body }, res) {
        let messaging_events = body.entry[0].messaging;
        for (let i = 0; i < messaging_events.length; i++) {
          let event = body.entry[0].messaging[i];
          let sender = event.sender.id;

          if (event.message) {
            self._handleEvent('message', event)
          }

          if (event.postback) {
            self._handleEvent('postback', event)
            if (event.postback.payload) {
              self._handleEvent(`postback:${event.postback.payload}`, event)
            }
          }

          if (event.delivery) {
            self._handleEvent('delivery', event)
          }
        }
        res.sendStatus(200);
      }
    });
  }
Exemplo n.º 2
0
export default function(name, model) {
	return resource({
		id : name,

		list({ params }, res) {
			var limit = Math.max(1, Math.min(50, params.limit|0 || 10));

			// if you have fulltext search enabled.
			if (params.search && typeof model.textSearch==='function') {
				return model.textSearch(params.search, {
					limit : limit,
					language : 'en',
					lean : true
				}, toRes(res));
			}

			model.find({}).skip(params.start|0 || 0).limit(limit).exec(toRes(res));
		},

		create({ body }, res) {
			model.create(body, toRes(res));
		},

		read({ params }, res) {
			model.findById(params[name], toRes(res));
		},

		update({ body, params }, res) {
			delete body._id;
			model.findByIdAndUpdate(params[name], { $set:body }, toRes(res));
		},

		delete({ params }, res) {
			model.findByIdAndRemove(params[name], toRes(res));
		}
	});
}
Exemplo n.º 3
0
export default resource({

	/** Property name to store preloaded entity on `request`. */
	id : 'facet',

	/** For requests with an `id`, you can auto-load the entity.
	 *  Errors terminate the request, success sets `req[id] = data`.
	 */
	load(req, id, callback) {
		var facet = facets.find( facet => facet.id===id ),
			err = facet ? null : 'Not found';
		callback(err, facet);
	},

	/** GET / - List all entities */
	index({ params }, res) {
		res.json(facets);
	},

	/** POST / - Create a new entity */
	create({ body }, res) {
		body.id = facets.length.toString(36);
		facets.push(body);
		res.json(body);
	},

	/** GET /:id - Return a given entity */
	read({ params }, res) {
		res.json(req.facet);
	},

	/** PUT /:id - Update a given entity */
	update({ facet, body }, res) {
		for (let key in body) {
			if (key!=='id') {
				facet[key] = body[key];
			}
		}
		res.sendStatus(204);
	},

	/** DELETE /:id - Delete a given entity */
	delete({ facet }, res) {
		facets.splice(facets.indexOf(facet), 1);
		res.sendStatus(204);
	}
});
Exemplo n.º 4
0
export default ({ config }) => resource({

	/** Property name to store preloaded entity on `request`. */
	id : 'pilipili',

	/** For requests with an `id`, you can auto-load the entity.
	 *  Errors terminate the request, success sets `req[id] = data`.
	 */
	load(req, id, callback) {
		let pilipili = pilipilis.find( pilipili => pilipili.id===id ),
			err = pilipili ? null : 'Not found';
		callback(err, pilipili);
	},

  /** GET / - List all entities */
  index({ params }, res) {
    res.json(pilipilis);
  },


	/** POST / - Create a new entity */
	create({ body }, res) {
    console.log(body);
    let title = body.title | null;
    var options = {
      title          : body.title,    // optional, auto-generated as default
      publishKey     : null,    // optional, auto-generated as default
      publishSecurity : "static" // optional, can be "dynamic" or "static", "dynamic" as default
    };

    //console.log(JSON.stringify(options));

    hub.createStream(options, function(err, stream) {
      if (!err) {
        let streamEntry = {};
        streamEntry.publish = stream.rtmpPublishUrl();
        streamEntry.play = stream.rtmpLiveUrls();
        streamEntry.id = stream.id;
        streamEntry.title = stream.title;
        pilipilis.push(streamEntry);
        db.put('pilipili',JSON.stringify(pilipilis));
        res.json(streamEntry);
      } else {
        console.log(err + ' error code: ' + err.errorCode + ' http code: ' + err.httpCode);
        res.json({error:err})
      }
    });

	},

	/** GET /:id - Return a given entity */
	read({ pilipili }, res) {
    console.log(pilipili);
		res.json(pilipili);
	},

	/** PUT /:id - Update a given entity */
	update({ pilipili, body }, res) {
		//for (let key in body) {
		//	if (key!=='id') {
		//		pilipili[key] = body[key];
		//	}
		//}
		res.sendStatus(204);
	},

	/** DELETE /:id - Delete a given entity */
	delete({ pilipili }, res) {
    //pilipilis.splice(pilipilis.indexOf(pilipili), 1);
    //res.sendStatus(204);
    hub.getStream(pilipili.id, function(err, stream) {
      if (!err) {
        console.log(stream);
        stream.delete(function(err, data) {
          if (!err) {
            console.log(data);
            pilipilis.splice(pilipilis.indexOf(pilipili), 1);
            db.put('pilipili',JSON.stringify(pilipilis));
            res.sendStatus(204);
          } else {
            console.log(err + 'error code: ' + err.errorCode + 'http code: ' + err.httpCode);
            res.json({error:err})
          }

        });
      }
    });

	},
});
Exemplo n.º 5
0
const itemResource = resource({

    id : 'id',

    // called for any request URI with an :id component,
    // req.id is then available later in the chain.
    load(req, id, callback) {
        const op  = new ItemPersist(dbPath);
        op.byID(id).then( (item) => {
            const err = item ? null : 'not found';
            req.ItemPersist = op; // save the DB handle for later in the chain
            callback(err, item);
        }).catch( (err) => {
            next(err);
        });
    },

    // GET / - list all
    index({ params }, res) {
        const op  = new ItemPersist(dbPath);
        op.all().then( (items) => {
            res.send(res.json(items));
        }).catch( (err) => {
            next(err);
        });
    },

    // GET /:id - return the given item
    read({ id }, res) {
        res.json(id);
    },

    // POST / - add a new item
    create({ body }, res) {
        const op  = new ItemPersist(dbPath);
        op.add(body).then( (item) => {
            res.send(res.json(item));
        }).catch( (err) => {
            next(err);
        });
    },

    // PUT /:id - update the given item
    update({ id, itemPersist, body }, res) {
        for (let key in body) {
            if (key !== 'id') {
                id[key] = body[key];
            }
        }
        itemPersist.update(id).then( () => {
        res.sendStatus(204);
        }).catch( (err) => {
            next(err);
        });
    },

    // DELETE /:id - delete the given item
    delete({ id, itemPersist }, res) {
        itemPersist.deleteByID(id.id).then( () => {
        res.sendStatus(204);
        }).catch( (err) => {
            next(err);
        });
    }

});
Exemplo n.º 6
0
export default resource({
    mergeParams: true,
    
	/** Property name to store preloaded entity on `request`. */
	id : 'music',

	/** For requests with an `id`, you can auto-load the entity.
	 *  Errors terminate the request, success sets `req[id] = data`.
	 */
    
	load(req, id, callback) {        
		var mus = music.find( mus => mus.id==id ),
		  err = mus ? null : 'Not found';
        
		callback(err, mus);
	},
    
	/** GET / - List all entities */
	index({ params }, res) {         
        //var mus = music.find( m => m.cat_id==params.id )
        var mus = []
        for (var value of music) {
            if(value.cat_id == params.id){
                mus.push(value);
            }
        }
            
        
		res.json(mus);
	},

	/** POST / - Create a new entity */
	create({ body }, res) {
		body.id = music.length.toString(36);
		music.push(body);
		res.json(body);
	},

	/** GET /:id - Return a given entity */
	read(req, res) {   
		res.json(req.music);
	},

	/** PUT /:id - Update a given entity */
	update({ facet, body }, res) {
		for (let key in body) {
			if (key!=='id') {
				facet[key] = body[key];
			}
		}
		res.sendStatus(204);
	},

	/** DELETE /:id - Delete a given entity */
	delete({ facet }, res) {
		music.splice(music.indexOf(facet), 1);
		res.sendStatus(204);
	}
});
Exemplo n.º 7
0
export default resource({

	/** Property name to store preloaded entity on `request`. */
	id : 'member',

	load(req, id, callback) {
		console.log('url = ' + req.url);
		console.log('params = ' + JSON.stringify(req.params));
		let member = find(id);
		let	err = member ? null : 'Not found';
		callback(err, member);
	},

	/** GET / - List all entities */
	index({ params }, res) {
		res.json(all());
	},

	/** POST / - Create a new entity */
	create({ body }, res) {
		body.id = team.length.toString(36);
		member.push(body);
		res.json(body);
	},

	/** GET /:id - Return a given entity */
	read({ div }, res) {
		res.json(div);
	},

	/** PUT /:id - Update a given entity */
	update({ div, body }, res) {
		for (let key in body) {
			if (key!=='id') {
				div[key] = body[key];
			}
		}
		res.sendStatus(204);
	},

	/** DELETE /:id - Delete a given entity */
	delete({ div }, res) {
		member.splice(member.indexOf(div), 1);
		res.sendStatus(204);
	}
});
Exemplo n.º 8
0
export default resource({

    id: 'product',

    index(req, res) {
        let limit = req.query.limit ? req.query.limit : 10;
        prestashopWS.get('products', {
            'display': 'full',
            'limit': limit,
            'sort': '[id_ASC]',
            'price[price][use_tax]': 1
        }).then(function(response) {
            if(!response.prestashop.products.product) {
                console.log('No products found!');
                res.status(404).json({status: 404, message: 'Product not found'});
                return;
            }
            if(!response.prestashop.products.product.length) {
                console.log('Product received');
                var prod = response.prestashop.products.product;
                var p = new Product(prod);
                p.prepareAssociations().then(() => {
                    res.json([p]);
                });
                return;
            } else {
                console.log(response.prestashop.products.product.length + ' Products received');
                let promises = [];
                let prods = [];
                response.prestashop.products.product.forEach(e => {
                    var p = new Product(e);
                    let promise = p.prepareAssociations().then(() => {
                        prods.push(p);
                    });
                    promises.push(promise);
                });
                return Promise.all(promises).then(() => {
                    return generator.generate('views/catalog.ejs', {
                        products: prods,
                        options: {
                            pageURL : PAGE_URL
                        }
                    });
                })
                .then((data) => {
                    res.json(prods);
                })
                .catch(err=>{
                    res.status(404).json({status: 404, message: err});
                });
            }
        }).catch(function(errors) {
            console.log(errors);
            res.status(404).json({status: 404, message: 'Product not found'});
        });
    },

    read(req, res) {
        prestashopWS.get('products', {
            'id': req.params.product,
            'price[price][use_tax]': 1
        }).then(function(response) {
            if(!response.prestashop.product) {
                console.log('No products found!');
                res.status(404).json({status: 404, message: 'Product not found'});
                return;
            }
            console.log('Product received');
            var prod = response.prestashop.product;
            var p = new Product(prod);
            let promises = [];
            promises.push(p.prepareAssociations());
            return Promise.all(promises).then(() => {
                    return generator.generate('views/product.ejs', {
                        product: p,
                        options: {
                            pageURL : PAGE_URL
                        }
                    });
                })
                .then((data) => {
                    res.json(p);
                })
                .catch(err=>{
                    res.status(404).json({status: 404, message: err});
                });
        }).catch(function(errors) {
            console.log(errors);
            res.status(404).json({status: 404, message: 'Product not found'});
        });
    }
});