2016-06-05 2 views
-1

после получения основ работы с node.js и среднего стека Мне нравится начинать с моего собственного проекта.Кэш/сохранение в db тела Json из запроса GET

Проблема в следующем:
Я не могу получить доступ к телу/атрибутам json запрашиваемого API, который мне нравится сохранять в mongodb и обновлять каждые 24 часа автоматически.

Что я пытаюсь:
Позвонить по 2 API'ам. Ответ теза с json-списком наборов данных, которые я пытаюсь объединить с тем же именем в мою схему мангуста. Использование body.param или response.param не работает.

Пример реакции запроса получим:?
url1/API/продукты/все

{ 
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/элемент/все ключ = apikey

{ 
    success: true, 
    num_items: 6713, 
    products: [ 
      { 
      product_name: "Product1", 
      .... 
      icon_url: "//url/economy/image/bla.png", 
      product_color: "8650AC", 
      quality_color: "EB4B4B" 
      }, 
      .... 

После того, как выяснить, что экспресс только маршруты к локальным URL-адресам, im используя запрос сейчас.
Вот мои маршруты/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; 

После написания этот вопрос, я думаю, что разве лучший способ приблизиться к этому. Есть ли лучшая практика?

+0

У вас есть несколько вопросов: 'res.body' должен быть' req.body', вы должны асинхронно перебирать массив (используйте пакет 'async'), отправить результат после сохранения всех данных –

ответ

0

У вас есть несколько вопросов:

  1. res.body должен быть req.body
  2. вы должны перебирать массив асинхронно (использование асинхронной пакет)
  3. результат посыла после сохранения всех данных

См. Образец ниже

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); 
      }); 
     } 
    }); 
}); 
+0

Спасибо за это, я попытался зарегистрировать все, что может помочь мне получить эти параметры тела, но все было не определено. Я использовал req.body до этого, почему im в конце. Хотя у меня есть тело-парсер как зависимость. Вот пример вывода '{ __v: 0, ID: "0", AppID: 730, updated_at: "2016-06-05T16: 18: 49.445Z", _id: "575450e9a3ad44e02a08615c", created_at: "2016-06-05T16: 18: 49.408Z" }, { __v: 0, ID: "1", AppID: 730, updated_at: "2016-06-05T16: 18: 49.469Z", _id: "575450e9a3ad44e02a08615d", created_at: "2016-06-05T16: 18: 49.430Z" } 'Как вы можете видеть, я не могу получить доступ к данным в корпусе json. –

+0

Это другой вопрос, откройте новый, так как это не так. 't fit to current –

Смежные вопросы