f-coder-server
TypeScript icon, indicating that this package has built-in type declarations

0.0.3 • Public • Published

Coder Server

This package is only some utility classes on top of express and zod to develop a small express server with validations with zod

Usage example

import { Server, Router } from 'coder-server';
const userRouter = new Router('/user');
userRouter
  .get(
    '/',
    (req, res) => {
      res.okResponse('this generates a 200 Http response');
    },
    (req, res, next) => {
      console.log('this is a middleware');
      next();
    },
  )
  .get('/:id', (req, res) => {
    res.userErrorResponse('this generates a 400 error response');
  });

const server = new Server();

server.setRouter(userRouter);

server.start(3000);

Validation Middlewares

You can also use validation middlewares

import { z } from 'zod';
import { Router, validateBody, validateParams, validator } from 'coder-server';
const UserDto = z.object({
  name: z.string().min(3).max(255),
  email: z.string().email(),
  role: z.enum(['admin', 'user']),
});
const Id = z.object({
  id: z.string().uuid(),
});

const userRouter = new Router('/user');
userRouter.put(
  '/:id',
  (req, res) => {
    res.okResponse('everything went ok');
  },
  validateParams(validator(Id)),
  validateBody(validator(UserDto)),
);

Setting several routes

There are two forms of setting routes on the server level:

server.setRouter(userRouter).setRouter(catsRoute);

//or

server.setRouters([userRouter, catsRoute]);

It is possible to set sub routes on the router level:

const userRouter = new Router('/user');

userRouter.subRoute(addressRouter);

Readme

Keywords

Package Sidebar

Install

npm i f-coder-server

Weekly Downloads

1

Version

0.0.3

License

ISC

Unpacked Size

17.4 kB

Total Files

16

Last publish

Collaborators

  • fpauselli