serverless frameworkλ₯Ό μ΄μ©νμ¬ κ°λ¨ν Lambda ν¨μλ₯Ό μμ±νκ³ λ°°ν¬ν©λλ€.
handler.js
νΈμ§ (μλ² κ΅¬ν)module.exports.hello = async (event) => {
let inputValue, outputValue
console.log(event.body)
if (event.body) {
let body = JSON.parse(event.body)
// μΆκ° λμ κ³Όμ : bodyκ° { input: μ«μ } κ° λ§λμ§ κ²μ¦νκ³ , κ²μ¦μ μ€ν¨νλ©΄ μλ΅μ½λ 400 λ° μλ¬ λ©μμ§λ₯Ό λ°ννλ μ½λλ₯Ό λ£μ΄λ΄
μλ€.
inputValue = parseInt(body.input)
outputValue = inputValue + 1
}
const message = `λ©μμ§λ₯Ό λ°μμ΅λλ€. μ
λ ₯κ°: ${inputValue}, κ²°κ³Ό: ${outputValue}`return {
statusCode: 200,
body: JSON.stringify(
{
message
},
null,
2
),
};
};
serverless deploy
λ₯Ό ν΅ν λ°°ν¬λ€μκ³Ό κ°μ΄ μμ²νμ¬ ν¨μ μ€νμ νμΈν μ μμ΅λλ€.
curl -X POST https://API_GATEWAY_ID.execute-api.ap-northeast-2.amazonaws.com \\ --header 'Content-type: application/json' \\ --data-raw '{ "input": 1 }'
npm install --global serverless
serverless
serverless.yaml μμ
service: aws-node-http-api-project
frameworkVersion: '3'
provider:
name: aws
runtime: nodejs18.x
region: ap-northeast-2
functions:
api:
handler: index.handler
events:
- httpApi:
path: /
method: post
index.js μμ
module.exports.hello = async (event) => {
let inputValue, outputValue
console.log(event.body)
if (event.body) {
let body;
try {
body = JSON.parse(event.body);
// μΆκ° λμ κ³Όμ : bodyκ° { input: μ«μ } κ° λ§λμ§ κ²μ¦νκ³ , κ²μ¦μ μ€ν¨νλ©΄ μλ΅μ½λ 400 λ° μλ¬ λ©μμ§λ₯Ό λ°ννλ μ½λλ₯Ό λ£μ΄λ΄
μλ€.
// μ
λ ₯νμΈ
if (typeof body.input !== 'number') {
return {
statusCode: 400,
body: JSON.stringify({
error: 'μ
λ ₯κ°μ΄ μ¬λ°λ₯΄μ§ μμ΅λλ€. μ«μλ₯Ό μ
λ ₯ν΄μ£ΌμΈμ.'
})
};
}
inputValue = parseInt(body.input);
outputValue = inputValue + 1;
} catch (error) {
return {
statusCode: 400,
body: JSON.stringify({
error: 'μ¬λ°λ₯Έ JSON νμμ΄ μλλλ€.'
})
};
}
}
const message = `λ©μμ§λ₯Ό λ°μμ΅λλ€. μ
λ ₯κ°: ${inputValue}, κ²°κ³Ό: ${outputValue}`
return {
statusCode: 200,
body: JSON.stringify(
{
message
},
null,
2
),
};
};