서버리스 함수의 가장 보편적 인 사용 사례 중 하나는 라우팅이 완료된 웹 서버를 배포하고 실행하는 것입니다.
이 자습서에서는 AWS Lambda, Amazon API Gateway 및 AWS Amplify를 사용하여 몇 분만에 이 함수를 시작하고 실행하는 방법을 보여줍니다.
https://dev.to/aws/10-minute-tutorial-creating-a-serverless-express-web-server-api-29j7
내가 사용할 라이브러리는 이 사용 사례를 위해 특별히 제작 된 Serverless Express 프로젝트입니다.
이 라이브러리를 사용하면 Express 서버에 이벤트 및 컨텍스트를 쉽게 프록시 할 수 있으며 여기에서 get, post, put 및 delete와 같은 다양한 경로 및 HTTP 메소드에 액세스 할 수 있습니다.
app.get('/', (req, res) => {
res.json(req.apiGateway.event)
})
시작하기
Lambda 함수를 배포하는 방법은 여러 가지가 있습니다. AWS 콘솔로 직접 이동하거나 서버리스 프레임 워크를 사용하거나 인프라를 코드로 사용하는 다양한 도구를 사용할 수 있습니다.
Amplify Framework에서 CLI 기반 접근 방식을 사용합니다.
시작하려면 먼저 Amplify CLI를 설치하고 구성하십시오.
CLI를 구성하는 방법에 대한 비디오 연습을 보려면 여기를 클릭하십시오.
$ npm install -g @aws-amplify/cli
$ amplify configure
이제 선택한 JavaScript 프레임 워크 (React, Angular, Vue 등)를 사용하여 프로젝트를 작성하십시오.
$ npx create-react-app myapp
$ cd myapp
$ npm install aws-amplify
다음으로 JS 프로젝트의 루트에서 새로운 Amplify 프로젝트를 초기화하십시오.
$ amplify init
# Answer the questions prompted by the CLI
이제 API와 웹 서버를 만들 수 있습니다. 이를 위해 Amplify add 명령을 사용할 수 있습니다.
$ amplify add api
? Please select from one of the below mentioned services: REST
? Provide a friendly name for your resource to be used as a label for this category in the project: myapi
? Provide a path (e.g., /items): /items (or whatever path you would like)
? Choose a Lambda source: Create a new Lambda function
? Provide a friendly name for your resource to be used as a label for this category in the project: mylambda
? Provide the AWS Lambda function name: mylambda
? Choose the function template that you want to use: Serverless express function
? Do you want to access other resources created in this project from your Lambda function? N
? Do you want to edit the local lambda function now? N
? Restrict API access: N
? Do you want to add another path? N
CLI는 다음과 같은 몇 가지 사항을 만들었습니다.
/items
route서버 코드를 열어 봅시다.
amplify/backend/function/mylambda/src/index.js를 엽니다. 다음은 ./app.js에있는 Express 서버에 프록시 된 이벤트 및 컨텍스트가 있는 기본 함수 핸들러입니다.
const awsServerlessExpress = require('aws-serverless-express');
const app = require('./app');
const server = awsServerlessExpress.createServer(app);
exports.handler = (event, context) => {
console.log(`EVENT: ${JSON.stringify(event)}`);
awsServerlessExpress.proxy(server, event, context);
};
그런 다음 amplify/backend/function/mylambda/src/app.js를 엽니다.
여기에, 우리가 선언 한 경로에 대한 다른 HTTP 메소드에 대한 익스프레스 서버 코드와 상용구가 표시됩니다. app.get ( '/ items')의 경로를 찾아서 다음으로 업데이트하십시오.
// amplify/backend/function/mylambda/src/app.js
app.get('/items', function(req, res) {
const items = ['hello', 'world']
res.json({ success: 'get call succeed!', items });
});
배포하기 전에 로컬에서 테스트 할 수 있지만 먼저 Lambda에 대한 종속성을 설치해야 합니다.
$ cd amplify/backend/function/mylambda/src && npm install && cd ../../../../../
함수를 호출하고 서버를 시작하려면 다음 명령을 실행하십시오.
$ amplify function invoke mylambda
이제 서버가 포트 3000에서 실행 중이며 이에 대한 요청을 할 수 있습니다. 명령 행에서 이를 수행하기 위해 다음 curl 명령을 실행할 수 있습니다.
$ curl http://localhost:3000/items
# {"success":"get call succeed!","items":["hello","world"]}%
API와 기능을 배포하기 위해 push 명령을 실행할 수 있습니다.
$ amplify push
이제 모든 JS 클라이언트에서 API와 상호 작용을 시작할 수 있습니다.
// get request
const items = await API.get('myapi', '/items')
// post with data
const data = { body: { items: ['some', 'new', 'items'] } }
await API.post('myapi', '/items', data)
여기에서 추가 경로를 추가 할 수 있습니다. 이렇게 하려면 update 명령을 실행하십시오.
$ amplify update api
여기에서 원격 경로를 추가, 업데이트 또는 수 있습니다.
API 카테고리에 대한 자세한 내용을 보려면 여기를 클릭하십시오.
등록된 댓글이 없습니다.