곰돌푸우❤️

목차

    이번 글에서는 Node.js에서 설치형 DynamoDB에 접근 설정과 샘플 코드를 작성해보겠습니다.

    • Node.js 프로젝트를 생성합니다.
    • AWS SDK for JavsScript를 설치합니다.
    $ npm install aws-sdk --save
    • 자격증명을 위한 키를 생성합니다. (DynamoDB에 접근하기 위해서는 권한이 필요합니다.)
      참고 : https://aws.amazon.com/ko/sdk-for-node-js/
      • IAM Console에 접속합니다.
      • 유저를 생성합니다. (Users -> Add User)
      • 키를 생성합니다. (Users -> User 선택 -> Security credentials -> Create access key)
      • 생성 후에 키를 바로 확인 할 수 있고 Download .csv file버튼을 눌러 다운로드 후 확인 할 수 있습니다.
        Access key ID: AKIAIOSFODNN7EXAMPLE
        Secret access key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
    • Credential 파일을 생성하고 키를 입력합니다. (Mac/Linux는 ~/.aws/credential Windows는 C:\Users\USERNAME\.aws\credentials)
      • your_access_key에는 위에서 확인 한 access_key를 입력합니다.
      • your_secret_key에는 위에서 확인 한 secret_key를 입력합니다.
    [default]
    aws_access_key_id = your_access_key
    aws_secret_access_key = your_secret_key
    • 이전 글에서 실행시킨 로컬 DynamoDB에 Node.js가 접근하기 위해 설정이 필요합니다.
      • region에는 us-west-2
      • endpoint에는 http://localhost:8000 를 입력합니다.
    var  AWS = require('aws-sdk'); 
    AWS.config.update({
        region: "us-west-2",
        endpoint: "http://localhost:8000" 
    });
    var dynamodb = new AWS.DynamoDB();
    
    var params = {
        TableName: 'MusicChart',
        KeySchema: [
            { // Required
                AttributeName: 'company',
                KeyType: 'HASH',
            },
            { // Optional
                AttributeName: 'rank', 
                KeyType: 'RANGE', 
            }
        ],
        AttributeDefinitions: [
            {
                AttributeName: 'company',
                AttributeType: 'N', // (S | N | B) for string, number, binary
            },
            {
                AttributeName: 'rank',
                AttributeType: 'N', // (S | N | B) for string, number, binary
            }
        ],
        ProvisionedThroughput: { // required provisioned throughput for the table
            ReadCapacityUnits: 1, 
            WriteCapacityUnits: 1, 
        }
    };
    dynamodb.createTable(params, function(err, data) {
        if (err) {
            console.log(err); // an error occurred
        } else {
            console.log(data); // successful response
        }
    });

    위 코드를 실행시키면 MusicChart라는 테이블이 생성됩니다.
    이 코드를 바탕으로 DynamoDB 를 사용하는 프로그램을 개발하실 수 있습니다.
    다음 글에서는 DynamoDB 테이블과 항목을 다루는 여러 방법들을 코드로 알아보겠습니다.

    ※ 참고 : http://localhost:8000/shell/에 접근하면 로컬 DynamoDB를 다루는 여러 예제들과 함께 코드를 쉽게 실행해 볼 수 있습니다.

    facebook twitter googleplus kakaostory naver