javascript - Express node.js - Requesting JSON, processing it asyncronously -
with node.js app, i'm getting json data spreadsheet api. returns json of following.
{ "status":200, "success":true, "result":[ { "dribbble":"a", "behance":"", "blog":"http://blog.invisionapp.com/reimagine-web-design-process/", "youtube":"", "vimeo":"" }, { "dribbble":"", "behance":"", "blog":"http://creative.mailchimp.com/paint-drips/?_ga=1.32574201.612462484.1431430487", "youtube":"", "vimeo":"" } ] }
it's dummy data 1 thing that, need process values (blog urls) under blog differently. blog url, need open graph data i'm using module called open-graph-scraper
with data.js i'm getting whole json , it's available in route index.js data
i'm processing data
checking blog column. if it's match, loop values (blog urls) through open-graph-scraper module.
this give me open graph data of each blog url following example json.
{ data: { success: 'true', ogimage: 'http://davidwalsh.name/wp-content/themes/punky/images/logo.png', ogtitle: 'david walsh - javascript, html5 consultant', ogurl: 'http://davidwalsh.name/', ogsitename: 'david walsh blog', ogdescription: 'david walsh blog features tutorials mootools, jquery, dojo, javascript, php, css, html5, mysql, , more!' }, success: true }
so goal pass blog json separate data main json , put in render separate object it's available in view 2 separate json. i'm not sure if approach getblogdata
correct. i'm not sure if processing data thing in router file. appreciate directions.
index.js
var ogs = require('open-graph-scraper'); var data = require('../lib/data.js'); data( function(data) { var getblogdata = function (callback) { var blogurl = []; if (data.length > 0) { var columnsin = data[0]; for(var key in columnsin) { if (key === 'blog') { for(var = 0; < data.length; i++) { blogurl += data[i][key]; } } } }; ogs({ url: blogurl }, function(er, res) { console.log(er, res); callback(res); }); } getblogdata( function (blogdata) { //i want make blogdata available in render below don't know how }); router.get('/', function(req, res, next) { res.render('index', { title: 'express', data: data }); }); });
data.js (my module gets json data)
module.exports = function(callback) { var request = require("request") var url = "http://sheetsu.com/apis/94dc0db4" request({ url: url, json: true }, function (error, response, body) { if (!error && response.statuscode === 200) { var results = body["result"]; callback(results) } }) }
the problem you'll have if getblogdata asynchronously (and should, don't want client waiting around data return), time data res.render have been called. can't call res.render again, have 2 options come mind:
- you query individual blog data client. result in more back-and-forth between client , server strategy if have lot of entries in initial data want display small number.
- you use websockets send data client retrieve it. express.io easy way this.
Comments
Post a Comment