2020年だが、Node.js 6を使う必要がある、標準モジュールを使わなくてはいけない、という制約下で複数のAPIを順番に実行していく必要がある場合のメモ。まぁ自分用のスニペット。
async / await は使えないのでPromiseで頑張る。async / await 使いたい。つらい。でもJavaScript使えるだけ有り難いといえばそう。
目次
環境
- node.js 6.11.0
- 標準のhttpモジュール
サンプル
POST先として、 https://webhook.site に順番に投げるようなイメージ。
var http = require('http');
var https = require('https');
var qs = require('querystring')
function callApi(host, port, method, path, body=undefined, content='json') {
console.log(`call api: ${method} ${host}:${port}${path}`)
return new Promise((resolve, reject) => {
let options = {
host: host,
port: port,
method: method,
path: path,
};
let payload;
if (content === "json") {
payload = body ? JSON.stringify(body) : null
options.headers = {
'Content-Type': 'application/json',
}
} else if (content == "url") {
payload = body ? qs.stringify(body) : null
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
console.log(`options: ${JSON.stringify(options)}, payload: ${payload}`);
const http_protocaol = port == 443 ? https : http
const req = http_protocaol.request(options, function(res) {
console.log(res.statusCode);
res.on('data', (chunk) => {
console.log(chunk.toString());
});
res.on('end', () => {
return resolve('hogehoge');
})
});
req.on('error', function(e) {
console.log(`error: ${e.message}`);
return reject(e);
});
if (payload) {
req.write(payload);
}
req.end();
});
}
function postRequest(val) {
return new Promise((resolve, reject) => {
callApi('webhook.site', 443, 'POST', '/webhook.site開いた時に出たパス', {test: val}, "json")
.then(result => {
return resolve(result.toString());
});
});
}
postRequest(1)
.then(postRequest.bind(this, 2))
.then(postRequest.bind(this, 30))
補足。443はhttps、それ以外のポートはhttpにしている。無駄にurlencodedにも対応している。
参考
ありがとうございました。
コメント