[Node.js] S3からjsonをdownload

$ npm install aws-sdk

s3.js

const express = require('express')
const AWS = require('aws-sdk')
var fs = require('fs')

const app = express()

const s3Client = new AWS.S3({
	accessKeyId: '',
	secretAccessKey: '',
	region: 'ap-northeast-1'
})

const params = {
	Bucket: 'hogehoge',
	Key: 'address.json',
}

s3Client.getObject(params, function(err, data){
	if(err){
		console.log(err, err.stack);
	} else {
		var object = JSON.parse(data.Body.toString());
		fs.writeFile('hoge.json', JSON.stringify(object), function(err, result){
			if(err) console.log('error', err);
		});
	}
})


const jsonObject = JSON.parse(fs.readFileSync('hoge.json', 'utf8'));
console.log(jsonObject);


app.listen(8000, () => console.log('Server Now Running'));

これをgraphQLに応用すると、mysqlから取得した場合も、connection.queryで一時保存し、jsonを読み込んでfilterで処理できますね。ちょっと冗長ではありますが。

  connection.query(
    'SELECT * FROM master_zip',
    (error, results) => {
      var object = JSON.parse(JSON.stringify(results));
      fs.writeFile('address.json', JSON.stringify(object), function(err, result){
        if(err) console.log('error', err);
      });
    }
);

var getAddress = function(args){

	var zip_code = args.zip_code;
  const jsonObject = JSON.parse(fs.readFileSync('address.json', 'utf8'));

  return jsonObject.filter(address => {
      return address.zip_code == zip_code;
  })[0];
}