从GET请求缓存/保存到Json Body的数据库 [英] Cache/save to db a Json Body from a GET request
问题描述
在了解了如何使用node.js和均值堆栈的基础知识之后,我想从我自己的项目开始.
after getting the basics of how to work with node.js and the mean stack i like to start with my own project.
问题是:
我无法访问请求的API的json正文/属性,我希望将其保存到mongodb并每24小时自动更新一次.
The Problem is:
I´m not able to access the json body/attributes of a requested API which i like to save to mongodb and update every 24h automatically.
我正在尝试什么:
就是要调用2个API.这些响应带有数据集的json列表,我尝试将其以相同的名称合并到我的猫鼬模式中.使用body.param或response.param无效.
What im trying:
Is to call 2 API´s. Theses response with a json list of datasets which i try to merge by the same name into my mongoose Schema. Using body.param or response.param, didnt work.
获取请求的示例响应:
url1/api/products/all
Example responses of a get request:
url1/api/products/all
{
data: [
{
id: 1,
product_name: "Product1",
app: appName,
quantity: 137360,
price: 0.05,
updated_at: "2016-06-04 23:02:03",
median_week: 0.04,
median_month: 0.05,
},
.....
{
id:142640
...
}
}
url2/api/item/all?key = apikey
url2/api/item/all?key=apikey
{
success: true,
num_items: 6713,
products: [
{
product_name: "Product1",
....
icon_url: "//url/economy/image/bla.png",
product_color: "8650AC",
quality_color: "EB4B4B"
},
....
发现仅表示到达本地网址的路由后,我立即使用了请求.
那是我的路线/item.js
After finding out that express only routes to local urls, im using request now.
Thats my routes/item.js
var express = require('express');
var qs = require('querystring');
var request = require('request');
var _ = require('underscore');
var router = express.Router();
var Item = require('../models/item');
var options = {
url: 'url2' + ?key + app.config.url2.apikey ,
port: 80,
method: 'GET',
json:true
}
/* GET listing. */
router.get('/', function(req, res) {
request.get('url', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Prints JSON Body
//Iterate through each id of url1 and num_items of url2 and update collection
// Better to make another request method just to call the second api?
for each(item in body.id || body.num_items) {
var newItem = Item({
id: item[i],
product_name: ,
app: 'appName',
quantity: res.body.quantity,
price: res.body.price,
....
icon_url: res.body.,
name_color: res.body.,
quality_color: body.,
created_at: Date.now,
updated_at:
})
newItem.save(function(err) {
if (err) throw err;
console.log('Item created');
})
//return res.json(body);
}
}
res.sendStatus('304');
});
});
这是我的商品模型
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ItemSchema = new Schema({
id: String,
....
created_at: {
type: Date,
default: Date.now
},
updated_at: Date
});
var Item = mongoose.model('Item', ItemSchema);
ItemSchema.pre('save', function(next) {
var currentDate = new Date();
this.updated_at = currentDate;
if (!this.created_at)
this.created_at = currentDate;
next();
});
module.exports = Item;
写完这个问题后,我认为这不是解决这个问题的最佳方法.有什么最佳实践吗?
After writing this question, i think that isnt the best way to approach this. Is there any best practice?
推荐答案
您遇到了几个问题:
- res.body必须是req.body
- 您必须异步迭代数组(使用异步包)
- 保存所有数据后发送结果
请参阅下面的示例
router.get('/', function(req, res) {
// npm install async --save
var async = require('async');
request.get('url', function (error, response, body) {
if (error && response.statusCode !== 200) {
// request could not be completed
return res.send(400, {message: 'Something went wrong'});
} else {
// get the count
var iterator = body.id || body.num_items;
// iterate number of times
async.times(iterator, function(number, next){
// create your new object
var newItem = Item({
id: number,
product_name: ,
app: 'appName',
quantity: req.body.quantity, // <== not res.body
price: req.body.price,
icon_url: req.body.,
name_color: req.body.,
quality_color: body.,
created_at: Date.now
});
// save and call next (which is callback)
newItem.save(next);
}, function(timesErr, timesResult){
// if something failed, return error
// even if 1 item failed to save, it will return error
if(timesErr) {
return res.send(400, {message: 'Something went wrong'});
}
// send the list of saved items;
// or whatever you want
res.status(200).send(timesResult);
});
}
});
});
这篇关于从GET请求缓存/保存到Json Body的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!