constAWS=require('aws-sdk');consts3=newAWS.S3();constMongoClient=require('mongodb').MongoClient;constObjectId=require('mongodb').ObjectId;exports.lambdaHandler=async (event, context) => {constbucket=event.Records[0].s3.bucket.name;constkey=decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g,' ')); //key path 경로constparams= { Bucket: bucket, Key: key, };//키 경로의 중간부분에 디비에서 id값으로 쓰일 부분을 잘라 넘겨줌constparts=key.split('/');constid= parts[2];try {//await로 s3객체를 검사한뒤 (동기적으로) mongoDB관련 함수를 실행한다const { ContentType } =awaits3.getObject(params).promise();awaitmongodbConnect(`${id}`);return ContentType; } catch (err) {constmessage=`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);thrownewError(message); }};
asyncfunctionmongodbConnect(id) {consturl='[MONGODB_URL]';constclient=newMongoClient(url, { useNewUrlParser:true });// MongoDB 연결try {awaitclient.connect();console.log('Connected database.'); } catch (err) {console.log('Failed to connected database.'); }try {constdb=client.db('[DB]');constcollection=db.collection('[COLLECTION]');//id 값으로 조회하여 업데이트 원하는 항목을 업데이트함// 조건constquery= { _id:ObjectId(id)};// 업데이트constupdate= {$set: {status:true}};// 옵션constoptions= { returnOriginal:false };awaitcollection.findOneAndUpdate(query, update, options);console.log(id+' Update succeeded'); }catch (err) {console.log('Failed to update the state of the object. Check if the ObjectId exists in the database.'); }finally {// MongoDB 연결 해제client.close(); }}
template.yaml
CloudFormation 방식으로, 스택이라는 리소스를 생성하며 aws 로 배포가능하게 해줌
템플릿은 자신에게 맞게 잘 작성해주어야함 아래는 그냥 예시임
AWSTemplateFormatVersion:'2010-09-09'Transform: AWS::Serverless-2016-10-31Description:> s3lambda Sample SAM Template for s3lambda# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rstGlobals: Function: Timeout:3 MemorySize:128Resources: HelloWorldFunction: Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction Properties: CodeUri: hello-world/ Handler:app.lambdaHandler Runtime:nodejs16.x Architectures:- arm64 Policies:- S3CrudPolicy: BucketName:!Sub "bucket" Events: HelloWorld: Type:S3 # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Bucket: Ref: Bucket1 Events: s3:ObjectCreated:* Bucket1: Type: AWS::S3::Bucket# 아래 부분을 추가하여 배포하면 버킷을 새로 생성함# Properties:# BucketName:!Sub "bucket"
event.json
로컬 테스트용도로 사용함
위와 같이 코드를 작성후 람다를 실행하였을때 content type 을 가져오는걸 확인할 수 있었음