Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Body Validation Doesn't Work #402

Closed
anthonyalayo opened this issue May 1, 2022 · 8 comments
Closed

Body Validation Doesn't Work #402

anthonyalayo opened this issue May 1, 2022 · 8 comments

Comments

@anthonyalayo
Copy link

Describe the bug
Following the docs, body validation doesn't work.

To Reproduce
Steps to reproduce the behavior:

  1. Run npx create-next-app@latest --ts
  2. Follow the tutorial here to add next-api-decorators
  3. Add body validation to an API route
  4. Test a request that doesn't conform to the expected shape

Expected behavior
The body validation throws an error as seen in the docs.

Additional context
I attempted to use this library with a DTO similar to the examples:

class RequestBody {
    @IsEmail()
    email: string;

    @MinLength(6)
    @MaxLength(20)
    password: string;
}

But it was not validating the body, and no errors were thrown. Upon stepping into the code, I found that paramType here was being set to undefined:
https://github.com/storyofams/next-api-decorators/blob/master/lib/internals/handler.ts#L79-L82

Because my class was being compiled as an object:
image

Googling this, I found a StackOverflow with this answer:
https://stackoverflow.com/questions/526559/testing-if-something-is-a-class-in-javascript

So I'm concluding here that there must be some necessary setting required inside tsconfig that is not being specified in the project docs.

@ggurkal
Copy link
Member

ggurkal commented May 1, 2022

Hi @anthonyalayo,

It's not possible tell much about your problem without the code. Can you share it here?

@anthonyalayo
Copy link
Author

@ggurkal sure, it's a bit of a mess as I'm prototyping, but here is the class:

class RequestBody {
    @IsEmail()
    email: string;

    @MinLength(6)
    @MaxLength(20)
    password: string;
}

class Handler {
    @Post()
    async signIn(
        @Res() res: NextApiResponse,
        @Body(ValidationPipe) body: RequestBody,
    ) {
        return "test"
   }
}

export default createHandler(Handler)

And here is a jest test attempting to call the API (I got this from another discussion/issue):

it('signs in', async () => {
    const { req, res } = createMocks({
        method: 'POST',
        url: '/api/auth/signin',
        body: { 'test@test.com' }
    });

    await signin(req, res)
    expect(status).toEqual(400)
})

Here is my jest configuration:

  "jest": {
    "preset": "ts-jest",
    "setupFiles": [
      "dotenv/config"
    ]
  },

And I'm running this in WebStorm if that helps?

@anthonyalayo
Copy link
Author

Is there some known configuration that's needed when running with/without jest and next-api-decorators to make sure that classes don't get compiled as objects? That seems to be the main culprit that makes validators not work.

@ggurkal
Copy link
Member

ggurkal commented May 1, 2022

Thanks @anthonyalayo

Can you share your package.json, tsconfig.json files and your node version as well?

@anthonyalayo
Copy link
Author

anthonyalayo commented May 1, 2022

@ggurkal Yeah sure -- note these are mostly vanilla from a NextJS 12 generation.

tsconfig.json

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "strictPropertyInitialization": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

(I had to add "strictPropertyInitialization": false, for the project to compile. Could this be added to the docs?)

package.json

{
  "name": "test",
  "version": "0.1.0",
  "private": true,
  "jest": {
    "preset": "ts-jest",
    "setupFiles": [
      "dotenv/config"
    ]
  },
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@storyofams/next-api-decorators": "^1.7.2",
    "class-transformer": "^0.5.1",
    "class-validator": "^0.13.2",
    "next": "12.1.5",
    "node-mocks-http": "^1.11.0",
    "react": "18.0.0",
    "react-dom": "18.0.0"
  },
  "devDependencies": {
    "@types/jest": "^27.4.1",
    "@types/node": "17.0.25",
    "@types/react": "18.0.5",
    "@types/react-dom": "18.0.1",
    "autoprefixer": "^10.4.5",
    "dotenv": "^16.0.0",
    "eslint": "8.13.0",
    "eslint-config-next": "12.1.5",
    "jest-mock-extended": "^2.0.4",
    "ts-jest": "^27.1.4",
    "typescript": "4.6.3"
  }
}

node version:

 ❯ node --version
v17.9.0

@anthonyalayo
Copy link
Author

@ggurkal any idea what angle we can pursue for debugging?

@ggurkal
Copy link
Member

ggurkal commented May 3, 2022

Yes @anthonyalayo

The target flag in the tsconfig.json should be equal to or higher than es5. The minimum value ises6.

Will add it into the docs as well.

Let me know the outcome.

@anthonyalayo
Copy link
Author

That worked, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants