How to use rulr - 10 common examples

To help you get started, we’ve selected a few rulr examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github kube-js / kube-ts-server / src / presenter / express / api / v1 / routes / users / functions / beforeUpdateItem / index.ts View on Github external
beforeHandler: async ({ req }: HookOptions) => {
      const user = await getAuthenticatedUser({ req, config });

      // FYI: user should be able to update itself without permission
      if (req.params.id !== user.id) {
        await hasPermission({ req, user, config });
      }

      const payload: any = _pick(Object.keys(schema), req.body);

      validateData(rules)(payload);

      req.body.password = !_isNil(req.body.password)
        ? await hashPassword(req.body.password)
        : undefined;
        
      req.body.updatedAt = getUtcDate();
    },
    config,
github kube-js / kube-ts-server / src / presenter / express / api / v1 / routes / courses / functions / beforeCreateItem / index.ts View on Github external
beforeHandler: async ({ req }: HookOptions) => {
      const user = await getAuthenticatedUser({ req, config });

      await hasPermission({ req, user, config });

      const payload: any = _pick(Object.keys(beforeCreateSchema), req.body);

      validateData(rules)(payload);

      // user who has permission to create an article is an author
      req.body.user_id = user.id;
    },
    config,
github kube-js / kube-ts-server / src / presenter / express / api / v1 / routes / users / functions / beforeReplaceItem / index.ts View on Github external
beforeHandler: async ({ req }: HookOptions) => {
      const user = await getAuthenticatedUser({ req, config });

      // FYI: user should be able to update itself without permission
      if (req.params.id !== user.id) {
        await hasPermission({ req, user, config });
      }

      const payload: any = _pick(Object.keys(schema), req.body);

      validateData(rules)(payload);

      req.body.password = !_isNil(req.body.password)
        ? await hashPassword(req.body.password)
        : undefined;

      req.body.updatedAt = getUtcDate();
    },
    config,
github kube-js / kube-ts-server / src / presenter / commander / functions / dbSeed / functions / createUser / index.ts View on Github external
// tslint:disable:no-console
// tslint:disable:no-magic-numbers
import faker from 'faker';
import promptly from 'promptly';
import Record from 'rulr/Record';
import validateData from 'rulr/validateData';
import { v4 as uuid } from 'uuid';
import { VARCHAR_LENGTH } from '../../../../../../constants';
import hashPassword from '../../../../../../utils/helpers/auth/hashPassword';
import getUtcDate from '../../../../../../utils/helpers/date/getUtcDate';
import Email from '../../../../../../utils/validation/rules/Email';
import String from '../../../../../../utils/validation/rules/String';
import FactoryConfig from '../../../../presenterFactory/FactoryConfig';

const rules = Record({
  email: Email(),
  // FYI: intential just String validation on password,
  // allowing weak passwords for development
  password: String(0, VARCHAR_LENGTH),
});

export interface Options {
  readonly userType: string;
  readonly defaultEmail: string;
  readonly defaultPassword: string;
  readonly rolesIds: string[];
}

const createUser = (config: FactoryConfig) => async ({
  defaultEmail,
  defaultPassword,
github mariocoski / rest-api-node-typescript / src / utils / validate / index.ts View on Github external
}

export const maxLength = (length: number, rule?: Rule): Rule => (data, path) => {
  return data.length <= length ? (rule? rule(data,path) : []) : [createMaxLengthWarning(data, path, length)];
}

export const isSortValid = (data: string = ""):boolean => {
  const pattern =  /^([a-z_]+:(?:asc|desc))(?:,([a-z_]+:(?:asc|desc)))*$/ig
  return pattern.test(data);
}

export const isValidSortObject = (rule?: Rule): Rule => (data, path) => {
  return isSortValid(data) ? (rule? rule(data,path) : []) : [createInvalidSortObjectWarning(data, path)];
}

export const isEmail = checkRegex(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, createInvalidEmailWarning)
github mariocoski / rest-api-node-typescript / src / presenter / express / users / updateUser / index.ts View on Github external
import hasPermission from '../../../../utils/jwt/hasPermission';
import { CAN_UPDATE_USER } from '../../../../utils/constants';
import { minLength, isEmail, validateMatchingPasswords } from '../../../../utils/validate';
import { maybe, optional, checkType, composeRules, first, restrictToSchema }from 'rulr';
import * as R from 'ramda';

const validateUpdateUser = maybe(composeRules([
  restrictToSchema({
    firstname: optional(checkType(String)),
    lastname: optional(checkType(String)),
    bio: optional(checkType(String)),
    email: optional(isEmail),
    password: optional(minLength(6)),
    password_confirmation: optional(checkType(String)),
  }),
  first(checkType(Object), optional(validateMatchingPasswords))
]));

export default (config: Config) => {
  return catchErrors(config, async (req, res) => {
  
    const { permissions } = await getAuthUserAndPermissions({req, service: config.service});
    
    hasPermission({permissions, permissionName: CAN_UPDATE_USER});
 
    validateUpdateUser(req.body, ['user']);
    
    const {user_id} = req.params;

    const fillable = [
      'firstname', 'lastname', 'bio', 'email', 'password'
    ];
github mariocoski / rest-api-node-typescript / src / presenter / express / posts / getPosts / index.ts View on Github external
import Config from '../../Config';
import catchErrors from '../../utils/catchErrors';
import { Request, Response } from 'express';
import { OK } from 'http-status-codes';
import getAuthUserAndPermissions from '../../../../utils/jwt/getAuthUserAndPermissions';
import hasPermission from '../../../../utils/jwt/hasPermission';
import { CAN_GET_POSTS } from '../../../../utils/constants';
import { maybe, optional, checkType, restrictToSchema }from 'rulr';
import { isValidSortObject } from '../../../../utils/validate';

const validateGetPosts = maybe(
  restrictToSchema({
    limit: optional(checkType(String)),
    offset: optional(checkType(String)),
    sort: optional(isValidSortObject())
  }),
);

export default (config: Config) => {
  return catchErrors(config, async (req, res) => {
      
    const { permissions } = await getAuthUserAndPermissions({req, service: config.service});
    
    hasPermission({ permissions, permissionName: CAN_GET_POSTS});

    validateGetPosts(req.query,['posts']);

    const {limit, offset, sort} = req.query;

    const posts = await config.service.getPosts({limit, offset, order: sort});
github mariocoski / rest-api-node-typescript / src / presenter / express / users / updateUser / index.ts View on Github external
import Config from '../../Config';
import catchErrors from '../../utils/catchErrors';
import { OK } from 'http-status-codes';
import getAuthUserAndPermissions from '../../../../utils/jwt/getAuthUserAndPermissions';
import hasPermission from '../../../../utils/jwt/hasPermission';
import { CAN_UPDATE_USER } from '../../../../utils/constants';
import { minLength, isEmail, validateMatchingPasswords } from '../../../../utils/validate';
import { maybe, optional, checkType, composeRules, first, restrictToSchema }from 'rulr';
import * as R from 'ramda';

const validateUpdateUser = maybe(composeRules([
  restrictToSchema({
    firstname: optional(checkType(String)),
    lastname: optional(checkType(String)),
    bio: optional(checkType(String)),
    email: optional(isEmail),
    password: optional(minLength(6)),
    password_confirmation: optional(checkType(String)),
  }),
  first(checkType(Object), optional(validateMatchingPasswords))
]));

export default (config: Config) => {
  return catchErrors(config, async (req, res) => {
  
    const { permissions } = await getAuthUserAndPermissions({req, service: config.service});
    
    hasPermission({permissions, permissionName: CAN_UPDATE_USER});
 
    validateUpdateUser(req.body, ['user']);
    
    const {user_id} = req.params;
github mariocoski / rest-api-node-typescript / src / presenter / express / posts / getPosts / index.ts View on Github external
import Config from '../../Config';
import catchErrors from '../../utils/catchErrors';
import { Request, Response } from 'express';
import { OK } from 'http-status-codes';
import getAuthUserAndPermissions from '../../../../utils/jwt/getAuthUserAndPermissions';
import hasPermission from '../../../../utils/jwt/hasPermission';
import { CAN_GET_POSTS } from '../../../../utils/constants';
import { maybe, optional, checkType, restrictToSchema }from 'rulr';
import { isValidSortObject } from '../../../../utils/validate';

const validateGetPosts = maybe(
  restrictToSchema({
    limit: optional(checkType(String)),
    offset: optional(checkType(String)),
    sort: optional(isValidSortObject())
  }),
);

export default (config: Config) => {
  return catchErrors(config, async (req, res) => {
      
    const { permissions } = await getAuthUserAndPermissions({req, service: config.service});
    
    hasPermission({ permissions, permissionName: CAN_GET_POSTS});

    validateGetPosts(req.query,['posts']);

    const {limit, offset, sort} = req.query;
github mariocoski / rest-api-node-typescript / src / presenter / express / posts / updatePost / index.ts View on Github external
import Config from '../../Config';
import catchErrors from '../../utils/catchErrors';
import { OK } from 'http-status-codes';
import getAuthUserAndPermissions from '../../../../utils/jwt/getAuthUserAndPermissions';
import hasPermission from '../../../../utils/jwt/hasPermission';
import { CAN_UPDATE_POST, VARCHAR_FIELD_LENGTH, TEXT_FIELD_LENGTH } from '../../../../utils/constants';
import { maxLength } from '../../../../utils/validate';
import { maybe, optional, checkType,composeRules, restrictToSchema }from 'rulr';

const validateUpdatePost = maybe(composeRules([
  restrictToSchema({
    user_id: optional(checkType(Number)),
    title: optional(maxLength(VARCHAR_FIELD_LENGTH)),
    body: optional(maxLength(TEXT_FIELD_LENGTH)),
  })
]));

export default (config: Config) => {
  return catchErrors(config, async (req, res) => {
  
    const { permissions } = await getAuthUserAndPermissions({req, service: config.service});
    
    hasPermission({permissions, permissionName: CAN_UPDATE_POST});
 
    validateUpdatePost(req.body, ['post']);
    
    const {post_id} = req.params;
    
    const updatePost = await config.service.updatePost({id: post_id, data: req.body});

rulr

Validation and unit conversion errors in TypeScript at compile-time. Started in 2016.

MIT
Latest version published 4 days ago

Package Health Score

72 / 100
Full package analysis