mongoose#HookNextFunction TypeScript Examples

The following examples show how to use mongoose#HookNextFunction. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From server with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a Base64 Encoder Plugin which will add option to Encode Fields in a Schema
 *
 * @returns {Function} Base64 Plugin
 */
export default function <T, U extends Document, V extends Model<U>>(): (
  schema: Schema<U, V, T>,
) => void {
  const plugin = (schema: Schema<U, V, T>): void => {
    const toEncodeFields: string[] = fieldsPicker<T, U, V>(
      schema,
      'base64encode',
    );
    schema.pre('validate', function (this: U, next: HookNextFunction) {
      const encodedDoc = encodeFields<U>(this, toEncodeFields);
      this.set(encodedDoc);
      next();
    });
    schema.post('init', function (this: U) {
      const decodedDoc = decodeFields<U>(this, toEncodeFields);
      return decodedDoc;
    });
  };
  return plugin;
}
Example #2
Source File: index.ts    From server with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a Crypto Plugin which will add option to encrypt Fields in a Schema
 *
 * @returns {Function} Crypto Plugin
 */
export default function <T, U extends Document, V extends Model<U>>(): (
  schema: Schema<U, V, T>,
) => void {
  const plugin = (schema: Schema<U, V, T>): void => {
    const encryptedFields: string[] = fieldsPicker<T, U, V>(schema, 'encrypt');
    schema.pre('validate', function (this: U, next: HookNextFunction) {
      const encryptedDoc = encryptFields(this, encryptedFields);
      this.set(encryptedDoc);
      next();
    });
    schema.post('init', function (this: U) {
      const decryptedDoc = decryptFields<U>(this, encryptedFields);
      return decryptedDoc;
    });
  };
  return plugin;
}
Example #3
Source File: index.ts    From server with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a Hash Plugin which will add option to hash Fields using Bcrypt in a Schema
 *
 * @returns {Function} Hash Plugin
 */
export default function <T, U extends Document, V extends Model<U>>(): (
  schema: Schema<U, V, T>,
) => void {
  const plugin = (schema: Schema<U, V, T>): void => {
    const toHashFields: string[] = fieldsPicker<T, U, V>(schema, 'hash');
    schema.pre('validate', function (this: U, next: HookNextFunction) {
      hashString<U>(this, toHashFields)
        .then((hashedDoc) => {
          this.set(hashedDoc);
          next();
        })
        .catch((err) => {
          console.log(err);
          next(new Error('Password Hashing Failed'));
        });
    });
  };
  return plugin;
}