javascript - Transforming JSON in a node stream with a map or template -
i'm relatively new javascript , node , learn doing, lack of awareness of javascript design patterns makes me wary of trying reinvent wheel, i'd know community if want present in form or another, i'm not looking specific code example below, nudge in right direction , should searching for.
i want create own private ifttt/zapier plugging data 1 api another.
i'm using node module request get data 1 api , post another.
request supports streaming neat things this:
request.get('http://example.com/api') .pipe(request.put('http://example.com/api2')); in between 2 requests, i'd pipe json through transform, cherry picking key/value pairs need , changing keys destination api expecting.
request.get('http://example.com/api') .pipe(apitoapi2map) .pipe(request.put('http://example.com/api2')); here's json sample source api: http://pastebin.com/ikytjcyk
and i'd send forward: http://pastebin.com/133rhsjt
the transformed json in case takes keys value of each objects "attribute" key , value each objects "value" key.
so questions:
is there framework, library or module make transform step easier?
is streaming way should approaching this? seems elegant way it, i've created javascript wrapper functions
requestaccess api methods, need figure out middle step.would possible create "templates" or "maps" these transforms? want change source or destination api, nice create new file maps source destination key/values required.
hope community can , i'm open , suggestions! :) open source project i'm working on, if involved, in touch.
yes you're on right track. there 2 stream libs point towards, through makes easier define own streams, , jsonstream helps convert binary stream (like request.get) stream of parsed json documents. here's example using both of started:
var through = require('through'); var request = require('request'); var jsonstream = require('jsonstream'); var _ = require('underscore'); // our function(doc) here called handle each // incoming document int attributes array of json stream var transformer = through(function(doc) { var steps = _.findwhere(doc.items, { label: "steps" }); var activeminutes = _.findwhere(doc.items, { label: "active minutes" }); var stepsgoal = _.findwhere(doc.items, { label: "steps goal" }); // push transformed document outgoing stream this.queue({ steps: steps.value, activeminutes: activeminutes.value, stepsgoal: stepsgoal.value }); }); request .get('http://example.com/api') // attributes.* here split json stream chunks // each chunk element of array .pipe(jsonstream.parse('attributes.*')) .pipe(transformer) .pipe(request.put('http://example.com/api2'));
Comments
Post a Comment