instantcommerce / next-api-decorators

Collection of decorators to create typed Next.js API routes, with easy request validation and transformation.
https://next-api-decorators.vercel.app
MIT License
409 stars 28 forks source link

Invoking api endpoint throws error #592

Closed Unicodist closed 1 year ago

Unicodist commented 1 year ago

I get error message when trying to invoke next js api

I have an api file:

import {Body, createHandler, Post, ValidationPipe} from "next-api-decorators";
import {MessageRequestDto} from "@/api-models/message/message-request-dto";
class MessageHandler {
    @Post()
    postMessage( @Body(ValidationPipe) body:MessageRequestDto ){
        return "Message sent";
    }
}

export default createHandler(MessageHandler)

Dependencies:


"@chakra-ui/react": "^2.5.5",
    "@prisma/client": "^4.13.0",
    "@types/node": "18.15.11",
    "@types/react": "18.0.35",
    "@types/react-dom": "18.0.11",
    "class-transformer": "^0.5.1",
    "class-validator": "^0.14.0",
    "eslint": "8.38.0",
    "eslint-config-next": "13.3.0",
    "next": "13.3.0",
    "next-api-decorators": "^2.0.2",
    "next-google-fonts": "^2.2.0",
    "prisma": "^4.13.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-github-calendar": "^4.0.0",
    "react-icons": "^4.8.0",
    "sweetalert2": "^11.7.3",
    "typescript": "5.0.4"

When I try to invoke the api endpoint, I get this error:

{"statusCode":500,"message":"An unknown error occurred.","errors":["An unknown error occurred."],"stack":"TypeError: Cannot read properties of undefined (reading 'length')\n at ......./node_modules/next-api-decorators/dist/internals/handler.js:45:50\n at Array.map (<anonymous>)\n at MessageHandler.runMainLayer (/home/ashura/WebstormProjects/mysite/node_modules/next-api-decorators/dist/internals/handler.js:41:62)\n at descriptor.value (......./node_modules/next-api-decorators/dist/internals/handler.js:105:32)\n at process.processTicksAndRejections (node:internal/process/task_queues:95:5)"}

Code from the client:

function handleSubmit(e: FormEvent<HTMLFormElement>) {
        e.preventDefault()

        console.log(message)

        fetch('/api/message', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(message)
        }).then(async function (res) {
            if (res.status == 200)
                Swal.fire({title: 'Success', text: 'Successfully send message'})
            else if (res.status == 500)
                Swal.fire({icon: 'error', text: 'Something Went wrong', title: 'Error'})
        })
    }

(Although it results the same if I called from postman)

ggurkal commented 1 year ago

Duplicate of https://github.com/instantcommerce/next-api-decorators/issues/457