Skip to content

Releases: Alexigbokwe/expresswebTS-Version

v3.3.0

22 Dec 20:13
48bf1a4
Compare
Choose a tag to compare

v3.3.0

Fixed

  • Environment file check
  • RequestBodyValidator middleware
  • App environment check for local, staging, and production
  • Auto framework discovery for remote procedure call (RPC)
  • Request validation
  • Redis facade
  • SQL Error Handle. NOTE: Only MySQL, Sqlite3, MSSQL, and PostgreSQL are officially supported
  • Fixed make service command ts-node maker make-service SERVICE_NAME
  • Custom validation rule

RequestBodyValidator middleware

This now extends FormRequest:

import FormRequest from "Elucidate/Validator/FormRequest";
import { Request, Response, NextFunction } from "Elucidate/HttpContext";

class RequestBodyValidator extends FormRequest {
  async handle(req: Request, res: Response, next: NextFunction) {
    req.validate = <T>(data: T, rules: object) => {
      return FormRequest.make<T>(data, rules);
    };

    await next();
  }
}

export default RequestBodyValidator;

Request validation

This also extends FormRequest

import FormRequest from "Elucidate/Validator/FormRequest";

type dataType = { email: string; password: string };

class LoginValidation extends FormRequest {
  /**
   * Handle login request validation.
   * @param {*} data | e.g request body
   */
  static async validate<T>(data: any) {
    return await this.make<T>(data, {
      email: "required|string|email|max:255",
      password: "required|string|min:8",
    });
  }
}

export { LoginValidation, dataType };

SQL Error Handle

With the new SQL error handler, SQPPD_repository is now imported differently:

import UsersModel from "App/Model/Users_model";
import { SQLPD_repository, errorHandler } from "Elucidate/Repository/SQLPD_repository";

class UserRepository extends SQLPD_repository {
  constructor() {
    super(UsersModel);
  }

  async getAllUsers() {
    return await new Promise(async (resolve, reject) => {
      try {
        let users = await this.getAll();
        resolve(users);
      } catch (error: any) {
        reject(errorHandler(error));
      }
    });
  }
}
export default UserRepository;

Custom validation rule

Even though ExpressWebJs provides a variety of helpful validation rules, you may wish to create some of your own rules. One method of registering custom validation rules is using rule objects. To generate a new rule object, you may use the make-rule Maker command. Let's use this command to generate a rule that verifies a string is uppercase. This rule will be placed in the App/Rules directory. If this directory does not exist, ExpressWebJs will create it when you execute the Maker command to create your rule:

  ts-node maker make-rule Uppercase

Once the rule has been created, we are ready to define its behavior. A rule object contains two methods: passes and errorMessage. The passes method receives the value and should return true or false depending on whether the value is valid or not. The errorMessage method should return the validation error message that should be used when validation fails:

import Rule from "Elucidate/Validator/Rule";

class UpperCase extends Rule {
  /**
   * Determin if the validation rule passes.
   * @param {string} attribute
   * @param {string | number | boolean} value
   * @returns boolean
   */
  public passes(value: string | number): boolean {
    if (value.toString().toUpperCase() === value) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * Get the validation error message
   * @returns string
   */
  public errorMessage(): string {
    return "The :attribute must be uppercase";
  }
}

new UpperCase();

Once the rule has been defined, you may attach it to a validator like so:

//UserValidator.ts
import FormRequest from "Elucidate/Validator/FormRequest";
import "App/Rules/UpperCase";

class UserValidation extends FormRequest {
  /**
   * Handle the request validation.
   * @param {*} data | e.g request body
   */
  async validate<T>(data: T) {
    return await FormRequest.make<T>(data, {
      first_name: "required|string|UpperCase",
      last_name: "required|string",
      email: "required|email",
      password: "required|string",
    });
  }
}

export default new UserValidation();

Our UpperCase rule is added to the first_name attribute.

Version 3.2

09 Oct 17:16
Compare
Choose a tag to compare

This version release contains type improvement and security fixes.

Bug Fixes

Repository findById method now returns a model object instead of. an array of objects.

findById();

Redis Facade: This helps you easily interact with your Redis database

import Redis from "Elucidate/Facade/Redis";

Redis.set("name", "Alex Igbokwe");

let name = Redis.get("name");

console.log(name); // will return Alex Igbokwe

Redis.delete ("name"); // will delete name

For Pub/Sub

   let channel  = 'notification',
   Redis.publish(channel,"new message from Alex Igbokwe");

   Redis.subscribe(channel);

   Redis.unSubscribe(channel);

Request Data Type: There has been an improvement in incoming request data typings. You can now pass in the type of request body you are expecting from your route.

interface AuthBody {
  id: string;
  first_name: string;
}

getAuthenticatedUser = async (req: Request<AuthBody>, res: Response, next: NextFunction) => {
  try {
    let user = await req.user;
    console.log(user.id); //user id
    console.log(user.first_name); //user first name
  } catch (error) {
    return next(error);
  }
};

Request Data Type Validation: There has been an improvement in request validation. You can now pass in the type of request body to be validated in the validate method.

interface IPost {
  title: string;
  body: string;
}

getAuthenticatedUser = async (req: Request, res: Response, next: NextFunction) => {
  try {
    let validate = await req.validate<IPost>(req.body);
    if (!validate.success) return HttpResponse.BAD_REQUEST(res, validate.data);

    let post = validate.data;
    console.log(post.title); // display validated post name
    console.log(post.body); // display validated post body
  } catch (error) {
    return next(error);
  }
};

Authenticator Token generator fix to accept both string, object, and buffer.