반응형

배경 설명

lambda에 S3를 연동시켜 두고, 해당 S3에 이벤트가 있을 때마다 람다를 실행시키는 코드를 해석해본다.

 

코드

const aws = require('aws-sdk');
const fs = require('fs');
var s3 = new aws.S3({ apiVersion: '2006-03-01' });


exports.handler = async(event, context,  callback) => {
    const bucket = event.Records[0].s3.bucket.name;

    console.log(event);   // 실행결과 테스트 1번
    console.log(event.Records);  // 실행결과 테스트 2번
    console.log(event.Records[0]);  // 실행결과 테스트 3번

    console.log(bucket); // 그럼 이건 .s3.bucket.name인 jane-bkt만 출력됨.
    const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); // 여기부턴 실행결과 2로 이동
    const params = {
        Bucket: bucket,
        Key: key,
    };
    var theObject = await s3.getObject(params).promise();
    const data = JSON.parse(theObject.Body);
    console.log(data);
    // console.log(theObject.Body.toString('utf8'));  // 위와 결과값이 같지만, 보기 좋은 형태로
        try {
        const { ContentType } = await s3.getObject(params).promise();
        console.log('CONTENT TYPE:', ContentType);
        console.log('********** Event generated by S3 ************* ');
        return ContentType;
        
    } catch (err) {
        console.log(err);
        const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
        console.log(message);
        throw new Error(message);
    }
};

 

 

실행 결과 1

1) console.log(event)

Function Logs
START RequestId: a4ff7ef5-b647-40b7-9e6d-8eb2fb95360f Version: $LATEST
2022-05-22T02:23:56.937Z a4ff7ef5-b647-40b7-9e6d-8eb2fb95360f INFO {
  Records: [
    {
      eventVersion: '2.0',
      eventSource: 'aws:s3',
      awsRegion: 'us-east-1',
      eventTime: '1970-01-01T00:00:00.000Z',
      eventName: 'ObjectCreated:Put',
      userIdentity: [Object],
      requestParameters: [Object],
      responseElements: [Object],
      s3: [Object]
    }
  ]
}

 2) console.log(event.Records);  // 실행결과 테스트 2번. 좀 더 자세히 나온다.

Function Logs
START RequestId: 35e8439b-4ac0-44fa-a006-85a3fdd6d4aa Version: $LATEST
2022-05-22T02:27:20.107Z 35e8439b-4ac0-44fa-a006-85a3fdd6d4aa INFO [
  {
    eventVersion: '2.0',
    eventSource: 'aws:s3',
    awsRegion: 'us-east-1',
    eventTime: '1970-01-01T00:00:00.000Z',
    eventName: 'ObjectCreated:Put',
    userIdentity: { principalId: 'EXAMPLE' },
    requestParameters: { sourceIPAddress: '127.0.0.1' },
    responseElements: {
      'x-amz-request-id': 'EXAMPLE123456789',
      'x-amz-id-2': 'EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH'
    },
    s3: {
      s3SchemaVersion: '1.0',
      configurationId: 'testConfigRule',
      bucket: [Object],
      object: [Object]
    }
  }
]


 3) console.log(event.Records[0]);  // 테스트 3번. 테스팅 json에서 언급한 jane-bkt, s3test.json을 포함한 결과값이 나온다.

Function Logs
START RequestId: cda13909-6eab-410a-9582-dc00d25732f2 Version: $LATEST
2022-05-22T02:28:47.364Z cda13909-6eab-410a-9582-dc00d25732f2 INFO {
  eventVersion: '2.0',
  eventSource: 'aws:s3',
  awsRegion: 'us-east-1',
  eventTime: '1970-01-01T00:00:00.000Z',
  eventName: 'ObjectCreated:Put',
  userIdentity: { principalId: 'EXAMPLE' },
  requestParameters: { sourceIPAddress: '127.0.0.1' },
  responseElements: {
    'x-amz-request-id': 'EXAMPLE123456789',
    'x-amz-id-2': 'EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH'
  },
  s3: {
    s3SchemaVersion: '1.0',
    configurationId: 'testConfigRule',
    bucket: {
      name: 'jane-bkt',
      ownerIdentity: [Object],
      arn: 'arn:aws:s3:::jane-bkt'
    },
    object: {
      key: 's3test.json',
      size: 1024,
      eTag: '0123456789abcdef0123456789abcdef',
      sequencer: '0A1B2C3D4E5F678901'
    }
  }
}

 

 

 

다시 코드

   const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); // 여기부턴 실행결과 2로 이동
   console.log(event.Records[0].s3.object.key.replace(/\+/g.''));  //  object.key에 +제거(/+) 및 전역으로 확장(/g) 

    const params = {
        Bucket: bucket,
        Key: key,
    };
    var theObject = await s3.getObject(params).promise();
    console.log(theObject);  // 결과 1)
    const data = JSON.parse(theObject.Body);
    console.log(data);
    // console.log(theObject.Body.toString('utf8'));  // 위와 결과값이 같지만 보기 좋은 형태로
        try {
        const { ContentType } = await s3.getObject(params).promise();
        console.log('CONTENT TYPE:', ContentType);
        console.log('********** Event generated by S3 ************* ');
        return ContentType;
        
    } catch (err) {
        console.log(err);
        const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
        console.log(message);
        throw new Error(message);
    }
};

 

실행결과 2

1)  console.log(theObject);  // 결과 1)

Function Logs
START RequestId: ed9a9525-9994-48da-8834-16ec0ab5c2d6 Version: $LATEST
2022-05-22T02:41:07.808Z ed9a9525-9994-48da-8834-16ec0ab5c2d6 INFO {
  AcceptRanges: 'bytes',
  LastModified: 2022-05-20T02:49:10.000Z,
  ContentLength: 80,
  ETag: '"5704c18c8279716da4b82c028dddb5d4"',
  ContentType: 'application/json',
  Metadata: {},
  Body: <Buffer 7b 0a 20 20 22 6e 61 6d 65 22 3a 20 22 4a 61 6e 65 22 2c 0a 20 20 22 61 67 65 22 3a 20 22 32 38 22 2c 0a 20 20 22 63 6f 6d 70 61 6e 79 22 3a 20 22 53 ... 30 more bytes> 
// 이 body를 아래 코드에서 JSON으로 파싱 후 출력함.
 const data = JSON.parse(theObject.Body);

}

 

Note

1) try - catch: 에러 핸들링 코드 (출처:https://ko.javascript.info/try-catch)

  1. try { } 안의 코드가 먼저 실행된다.
  2. 에러가 없다면, try 안의 마지막 줄까지 실행, catch 블록은 건너뜀
  3. 에러가 있다면, try 안 코드의 실행이 중단, catch(err) 블록으로 제어 흐름이 넘어감. 변수 err(아무 이름이나 사용 가능)는 무슨 일이 일어났는지에 대한 설명이 담긴 에러 객체를 포함. 
  try {
        const { ContentType } = await s3.getObject(params).promise();
        console.log('CONTENT TYPE:', ContentType);
        console.log('********** Event generated by S3 ************* ');
        return ContentType;
        
    } catch (err) {
        console.log(err);
        const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
        console.log(message);
        throw new Error(message);  // 에러 던지기.
    }
};

 

- event: 호출상황에 대한 정보.

- context: 실행되는 함수 환경에 대한 정보 

- callback: 응답을 전송하기 위한 함수. (Error 및 응답을 사용)

      -> 이벤트 루프가 비워질 때까지 기다린 다음, 응답이나 오류를 호출자에게 반환. 

- async: 비동기 핸들러를 sync 맞춰주기 위함. 

반응형

+ Recent posts