nodejs에서 dynamodb 사용하기
Section titled “nodejs에서 dynamodb 사용하기”ubuntu18 기준으로 작성하였습니다.
sudo apt install awscliaws configure실행하면 아래처럼 input이 차례대로 4개 나옵니다.
aws계정을 참고해서 복붙하세요~ 아래는 예시입니다.
AWS Access Key ID [None]: someAccessKeyAWS Secret Access Key [None]: someSecretKeyDefault region name [None]: ap-northeast-2Default output format [None]: json이렇게하면 aws cli는 끝입니다.
노드에서 aws-sdk를 사용할때, 방금 설정한 configure를 사용하게 됩니다.
노드 프로젝트에서 아래 명령어를 실행합니다.
npm install aws-sdk -S테이블 생성
Section titled “테이블 생성”const {AWS_REGION} = require('../../constants');
const AWS = require('aws-sdk');
AWS.config.update({ region: AWS_REGION,});
const docClient = new AWS.DynamoDB.DocumentClient();
module.exports = {AWS, docClient};const AWS_REGION = 'ap-northeast-2';const SURVEY_TABLE = 'moqa_web_survey';
module.exports = {AWS_REGION, SURVEY_TABLE};const {AWS} = require('../../config/dynamo');
const {SURVEY_TABLE} = require("../../../constants");
const dynamodb = new AWS.DynamoDB();
const params = { TableName: SURVEY_TABLE, KeySchema: [ {AttributeName: '_id', KeyType: 'HASH'}, ], AttributeDefinitions: [ {AttributeName: '_id', AttributeType: 'S'}, ], ProvisionedThroughput: { ReadCapacityUnits: 10, WriteCapacityUnits: 10 }};
dynamodb.createTable(params, function (err, data) { if (err) { console.error('Unable to create table. Error JSON:', JSON.stringify(err, null, 2)); } else { console.log('Created table. Table description JSON:', JSON.stringify(data, null, 2)); }});코드를 작성하고, 아래 명령어를 실행시킵니다.
node scripts/createSurveyTable.js테이블이름 같은 경우는, get post put delete할때도 써야하므로 별도의 constants.js에서 관리합니다.
테이블에서 데이터 조회
Section titled “테이블에서 데이터 조회”const findAll = () => { return new Promise((resolve, reject) => { const params = { TableName: SURVEY_TABLE, };
docClient.scan(params, function (err, data) { if (err) { console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2)); const {message, time} = err; reject({message, time}); } else { resolve(data.Items); } }); });};위 코드 블럭은 해당 테이블의 모든 데이터를 조회하는 function입니다.
express사용시, 라우팅은 위의 함수를 활용하여 아래와 같이 작성합니다.
router.get('/all', async (req, res, next) => { findAll().then(data => { res.status(200).send(data); }).catch(e => { res.status(500).send(e); });});모두 조회 후 author로 필터링
router.get('/author/:author', async (req, res, next) => { const {author} = req.params;
findAll().then(data => { const result = data.Items.filter(item => item.author === author); res.status(200).send(result); }).catch(e => { res.status(500).send(e); });});_id로 한개 조회하기
router.get('/:_id', async (req, res, next) => { const {_id} = req.params;
const params = { TableName: SURVEY_TABLE, Key: {_id} };
docClient.get(params, function (err, data) { if (err) { const {message, time} = err; res.status(500).send({message, time}); console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2)); } else { res.status(200).send(data.Item); } });});docClient의 scan메소드와는 다르게, get을 사용하면 key로 설정해놓은 컬럼들을 params의 Key라는 프로퍼티에 할당해야합니다.
sort key가 있다면, sort key도 넣어야합니다.
ref: https://docs.aws.amazon.com/ko_kr/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.html
Node.js에서 예외처리하기
Section titled “Node.js에서 예외처리하기”process.on("uncaughtException", error => { console.log("Oh my god, something terrible happend: ", error); process.exit(1); // exit application});process.on("unhandledRejection", (error, promise) => { console.log( " Oh Lord! We forgot to handle a promise rejection here: ", promise ); console.log(" The error was: ", error);});reference
https://softwareontheroad.com/nodejs-crash-exception-handler/
node에서 간편하게 letsencrypt를 사용하여 https 구현하는 방법
Section titled “node에서 간편하게 letsencrypt를 사용하여 https 구현하는 방법”먼저 인증서를 생성합니다.
인증서를 생성하기위해서는 먼저 도메인이 필요한데, 해당 과정은 여기서는 생략합니다.
greenlock 라이브러리를 사용합니다.
설명은 express기준으로 작성하였습니다만
express외에 koa, hapi 등의 모듈도 준비되어있습니다.
npm i greenlock-expressapp.js에서,
module.exports = app;위의 코드 바로 전 라인에 아래 코드를 추가하면 된다.
require("greenlock-express") .create({ version: "draft-11", configDir: "/etc/letsencrypt/", server: "https://acme-v02.api.letsencrypt.org/directory", email: "이메일", agreeTos: true, approvedDomains: ["도메인"], app, renewWithin: 81 * 24 * 60 * 60 * 1000, renewBy: 80 * 24 * 60 * 60 * 1000 }) .listen(80, 443);reference: https://git.coolaj86.com/coolaj86/greenlock-express.js
또 다른방법은 nginx로 reverse proxy를 구현하고, ssl을 붙이는 방법이 있긴하다. 그런데 위에 방법이 더 간편함..
하지만 어플리케이션의 구조가 커질수록 불리한 점이 많다.
npm install
Section titled “npm install”npm install은 package.json에 작성해놓은 dependency를 모두 설치하는 명령어이다.
기존에는 -S 옵션을 붙여야 dependencies에 설치가 되었지만, npm v5 이후로는 기본값이 되었다.
서버환경에서 npm install 했을때, permission 관련 에러가 났을때 임시 해결방법
sudo npm install --unsafe-perm=true --allow-rootsudo npm install ${name} --unsafe-perm=true --allow-root