|
| 1 | +var http = require('http'); |
| 2 | + |
| 3 | +module.exports = function getStockDataFromGoogle(context, req) { |
| 4 | + // Get comma-separated list of tickers from body or query |
| 5 | + var tickers = req.body.tickers || req.query.tickers; |
| 6 | + |
| 7 | + context.log(`Node.js HTTP trigger function processed a request. Getting ticker prices for ${tickers}`); |
| 8 | + |
| 9 | + // Return a promise instead of calling context.done. As our http response trigger is using the '$return' |
| 10 | + // binding, we can directly resolve the promise with our http response object, i.e. { status: ..., body: ... } |
| 11 | + return new Promise((resolve, reject) => { |
| 12 | + var responseBody = ""; |
| 13 | + http.get({ |
| 14 | + host: "www.google.com", |
| 15 | + path: `/finance/info?q=${tickers}` |
| 16 | + }) |
| 17 | + .on('response', (resp) => { |
| 18 | + // Build the response body as data is recieved via the 'data' event. |
| 19 | + // When the 'end' event is recieved, 'resolve' the promise with the built response. |
| 20 | + resp.on('data', (chunk) => responseBody += chunk) |
| 21 | + .on('end', () => resolve({ status: 200, body: parseGoogleFinance(responseBody) })); |
| 22 | + }) |
| 23 | + // If there is an error, 'resolve' with a 'Bad Request' status code and the error. |
| 24 | + // If instead we chose to 'reject' the promise (a good option with unknown/unrecoverable errors), |
| 25 | + // the client would receive a 500 error with response body {"Message":"An error has occurred."}. |
| 26 | + .on('error', (error) => resolve({ status: 400, body: error })) |
| 27 | + .end(); |
| 28 | + }); |
| 29 | + |
| 30 | + function parseGoogleFinance(responseBody) { |
| 31 | + // Strip extra characters from response |
| 32 | + responseBody = responseBody.replace('//', ''); |
| 33 | + |
| 34 | + var data = JSON.parse(responseBody); |
| 35 | + |
| 36 | + return data.reduce((accumulator, stock) => { |
| 37 | + // acc[ticker] = price |
| 38 | + accumulator[stock.t] = stock.l; |
| 39 | + return accumulator; |
| 40 | + }, {}); |
| 41 | + } |
| 42 | +} |
0 commit comments