All files / src/model inflector.ts

100% Statements 7/7
100% Branches 0/0
100% Functions 4/4
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41                        132x     132x 965x 932x 193x                                     132x 5x    
import inflection from 'inflection';
 
/** The inflection functions postgrelize uses; a library given to `useInflection` must provide them. */
export interface Inflection {
  /** Singular form of a word. */
  singularize: (word: string) => string;
  /** Plural form of a word. */
  pluralize: (word: string) => string;
  /** `snake_case` form of a name. */
  underscore: (word: string) => string;
}
 
let current: Inflection = inflection;
 
/** Inflector used for association names and `underscored` columns. */
export const inflector: Inflection = {
  singularize: (word) => current.singularize(word),
  pluralize: (word) => current.pluralize(word),
  underscore: (word) => current.underscore(word),
};
 
/**
 * Replaces the inflection library used to singularize and pluralize association names and to
 * underscore column names (Sequelize v6 `useInflection`). Call it before defining models.
 *
 * @param custom - Library with `singularize`, `pluralize` and `underscore`.
 * @see {@link Sequelize.useInflection}
 *
 * @example
 * ```ts
 * useInflection({
 *   singularize: (word) => word.replace(/s$/, ''),
 *   pluralize: (word) => `${word}s`,
 *   underscore: (word) => word.replace(/([A-Z])/g, '_$1').toLowerCase(),
 * });
 * ```
 */
export const useInflection = (custom: Inflection): void => {
  current = custom;
};