1.0.18 • Published 3 years ago

@oristic/common v1.0.18

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

Error Normalization

Example

$ npm i @oristic/common  --save
const {NotFoundError, BadRequestError, NotAuthorizedError} = require('@oristic/common');

// ES 2018 modules

import {NotFoundError, BadRequestError, NotAuthorizedError } from '@oristic/common';

Error Normalization

Handling HTTP error is easy now and do not worry about the consistent response body for all errors

Use errorHandler middleware to handle the error and produce respective response
import {express} from 'express';
import {errorHandler} from '@oristic/common';

const app = express();

app.use(errorHandler);

app.all('*', async (req, res) => {
  throw new NotFoundError();
});

app.listen(3000,() => consoe.log("App running on port 3000"));

You could throw BadRequest error when invalid credentials are passed

import express, { Response, Request } from 'express';
import { body } from 'express-validator';
import { validateRequest, BadRequestError } from '@oristic/common';
import { User } from '../models/User';
import { Password } from '../Services/password';
import jwt from 'jsonwebtoken';
const router = express.Router();

router.get(
  '/api/users/signin',
  [
    body('email').isEmail().withMessage('Email must be valid'),
    body('password').trim().notEmpty().withMessage('Password must be provided'),
  ],
  validateRequest,
  async (req: Request, res: Response) => {
    const { email, password } = req.body;
    const existingUser = await User.findOne({ email });

    if (!existingUser) {
      throw new BadRequestError('Invalid Credentials');
    }

    const passwordMatch = await Password.compare(
      existingUser.password,
      password
    );
    if (passwordMatch) {
      const userJwt = jwt.sign(
        {
          id: existingUser._id,
          email: existingUser.email,
        },
        process.env.JWT_KEY!
      );

      req.session = {
        jwt: userJwt,
      };

      return res.status(200).send(existingUser);
    }

    throw new BadRequestError('Invalid Credentials');
  }
);

Make use of RequestValidationError with exress-validation middleware

Use validateRequest as a middleware in your normal route with express-validator

import { Request, Response, NextFunction } from 'express';
import { validationResult } from 'express-validator';
import { RequestValidationError } from '@oristic/common';

export const validateRequest = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    throw new RequestValidationError(errors.array());
  }
  next();
};

Make use of DataBaseConnectionError

import {DataBaseConnectionError} from '@oristic/common';
const start = async () => {

  try {
    await mongoose.connect(process.env.MONGO_URI);
    console.log('Connected to MongoDB');
  } catch (error) {
    throw new DataBaseConnectionError(error);
  }

 start();
1.0.18

3 years ago

1.0.17

3 years ago

1.0.16

3 years ago

1.0.15

3 years ago

1.0.14

3 years ago

1.0.13

3 years ago

1.0.12

3 years ago

1.0.10

3 years ago

1.0.9

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.1

3 years ago

1.0.2

3 years ago

1.0.0

3 years ago