Na terceira aula no video Gerenciando estados, meu post deu certo, mas o get da o seguinte erro,
{
"currentRoute": "get - /api/results/65c784d0394c2c034f9e1676",
"error": "Serverless-offline: route not found.",
"existingRoutes": [
"post - /api/results",
"get - /api/results/:id"
],
"statusCode": 404
}
Aqui está o handler, mas no meu projeto está nomeado como index e fiz a alteração para index no serverless.yml e demais arquivos tbm
'use strict'
const { MongoClient, ObjectId } = require("mongodb")
async function connectToDatabase () {
const client = new MongoClient(process.env.MONGODB_CONNECTIONSTRING);
const connection = await client.connect();
return connection.db(process.env.MONGODB_DB_NAME)
}
function extractBody(event){
if (!event?.body) {
return {
statusCode: 422,
body: JSON.stringify({error: "Missing body"})
}
}
return JSON.parse(event.body)
}
module.exports.sendResponse = async (event) => {
const { name, answers } = extractBody(event)
const correctQuestions = [3, 1, 0, 2]
const totalCorrectAnswers = answers.reduce((acc, answer, index) => {
if (answer === correctQuestions[index]) {
acc++
}
return acc
}, 0)
const result = {
name,
answers,
totalCorrectAnswers,
totalAnswers: answers.length
}
const client = await connectToDatabase();
const collection = await client.collection("results");
const {insertedId} = await collection.insertOne(result)
return {
statusCode: 201,
body: JSON.stringify({
resultId: insertedId,
__hypermedia: {
href: `/results.html`,
query: { id: insertedId }
}
}),
headers: {
'Content-Type': 'application/json'
}
}
}
module.exports.getResult = async (event) => {
const client = await connectToDatabase();
const collection = await client.collection("results");
const result = await collection.findOne({
_id: new ObjectId(event.pathParameters.id)
});
if (!result) {
return {
statusCode: 404,
body: JSON.stringify({
error: 'Result not found'
}),
headers: {
'Content-Type': 'application/json'
}
}
}
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(result)
}
}
Aqui meu serverless.yml
org: guspucienik
app: gus-serverless
service: gus-serverless
frameworkVersion: '3'
params:
default:
dbName: alura-serverless
dev:
connectionString: mongodb://localhost:27017/alura-serverless
provider:
name: aws
runtime: nodejs18.x
environment:
MONGODB_CONNECTIONSTRING: ${param:connectionString}
MONGODB_DB_NAME: ${param:dbName}
functions:
sendResponse:
handler: api/index.sendResponse
events:
- httpApi:
path: /api/results
method: post
request:
schemas:
application/json: ${file(./schemas/sendResponse.json)}
getResult:
handler: api/index.getResult
events:
- httpApi:
path: /api/results/:id
method: get
plugins:
- serverless-offline