hoangvvo / next-connect

The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
https://www.npmjs.com/package/next-connect
MIT License
1.62k stars 65 forks source link

typescript: added export for types #176

Closed JasonMore closed 2 years ago

JasonMore commented 2 years ago

Summary

issue: https://github.com/hoangvvo/next-connect/issues/177

I wanted to use the middleware as part a toolset with:

But the type NextHandler isn't exported

How I fixed it

Export all the typescript types

Example code


import type { NextApiRequest, NextApiResponse } from 'next';
import nc from 'next-connect';
import { AnyZodObject, z } from 'zod';

export const LoginSchema = z.object({
  userId: z.string().min(2),
  password: z.string().min(6),
});

export type Login = z.infer<typeof LoginSchema>;

type Data = {
  name: string;
};

// this comes from next-connect but NC doesn't export it 🤔
type NextHandler = (err?: any) => void;

const validate =
  (schema: AnyZodObject) =>
  async (req: NextApiRequest, res: NextApiResponse, next: NextHandler) => {
    try {
      const body = JSON.parse(req.body);
      await schema.parseAsync(body);
      return next();
    } catch (error) {
      console.log('[LOG TODO]: validate error', error);
      return res.status(400).json(error);
    }
  };

const handler = nc({
  onError: (err, req: NextApiRequest, res: NextApiResponse, next) => {
    console.error(err.stack);
    res.status(500).end('Something broke!');
  },
  onNoMatch: (req: NextApiRequest, res: NextApiResponse, next) => {
    res.status(404).end('Page is not found');
  },
})
  .use(validate(LoginSchema))
  .get((req: NextApiRequest, res: NextApiResponse<Data>) => {
    res.json({ name: 'John Doe' });
  })
  .post((req, res) => {
    console.log('>>> req.body', req.body);
    res.json({ hello: 'world' });
  })
  .put(async (req, res) => {
    res.end('async/await is also supported!');
  })
  .patch(async (req, res) => {
    throw new Error('Throws me around! Error can be caught and handled.');
  });

export default handler;
changeset-bot[bot] commented 2 years ago

⚠️ No Changeset found

Latest commit: 21f0618d4740ec22a195878e3724f0f9a37a570e

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

codecov[bot] commented 2 years ago

Codecov Report

Merging #176 (21f0618) into master (3054aef) will not change coverage. The diff coverage is n/a.

Impacted file tree graph

@@            Coverage Diff            @@
##            master      #176   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            1         1           
  Lines           81        81           
=========================================
  Hits            81        81           

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update 3054aef...21f0618. Read the comment docs.

hoangvvo commented 2 years ago

Thanks!