WesTyler / joi-enums-extension

Joi extensions for enums mapping
Other
6 stars 5 forks source link

Version compatible with Joi 17 #4

Open ephys opened 4 years ago

ephys commented 4 years ago

Hi :)

I needed to update this library to make it work with Joi 17

Might as well give the updated code to you and anyone looking for a compatible version:

export const JoiExtensionEnumNumber = Joi => ({
  type: 'number',
  base: Joi.number(),
  messages: {
    'number.map': '"{{#label}}" must be a number or one of {{#enums}}',
  },
  coerce(value, helpers) {

    const map = helpers.schema.$_getFlag('mapping-number');
    if (!map || typeof value !== 'string') {
      return { value };
    }

    if (map[value] !== void 0) {
      return { value: map[value] };
    }

    return helpers.error('number.map', { value, enums: Object.keys(map) });
  },
  rules: {
    map: {
      args: [{
        name: 'mapping',
        ref: true,
        assert: arg => typeof arg === 'object' && arg !== null,
        message: 'must be an object',
      }],
      method(mapping) {
        return this.$_setFlag('mapping-number', mapping);
      },
    },
  },
});

export const JoiExtensionEnumAny = Joi => ({
  type: 'any',
  base: Joi.any(),
  messages: {
    'any.mapping': '"{{#label}}" must be one of {{#enums}}',
  },
  /* eslint-disable-next-line consistent-return */
  coerce(value, helpers) {

    const map = helpers.schema.$_getFlag('mapping-any');
    if (!map) {
      return { value };
    }

    if (map[value] !== void 0) {
      return { value: map[value] };
    }
  },
  validate(value, helpers) {
    const map = helpers.schema.$_getFlag('mapping-any');
    if (!map) {
      return null;
    }

    const validValues = Object.values(map);
    if (validValues.includes(value)) {
      return null;
    }

    return { value, errors: helpers.error('any.mapping', { value, enums: Object.keys(map) }) };
  },
  rules: {
    map: {
      args: [{
        name: 'mapping',
        ref: true,
        assert: arg => typeof arg === 'object' && arg !== null,
        message: 'must be an object',
      }],
      method(mapping) {
        return this.$_setFlag('mapping-any', mapping);
      },
    },
  },
});

export const JoiEnumExtensions = [JoiExtensionEnumNumber, JoiExtensionEnumAny];

// usage: Joi.extend(...JoiEnumExtensions);

N.B: Joi is only needed as a peer dependency with this version

WesTyler commented 4 years ago

Awesome, thanks for that! I'll leave this open for reference until I'm able to do a proper update and publish :)

phpstudyone commented 3 years ago

Hello, does this plugin play the same role as the latest symbol ?

ephys commented 3 years ago

Yes, but for other types than Symbol