Created
July 30, 2024 11:54
-
-
Save adevinwild/f85c3125649a142b09cf5d0aee628570 to your computer and use it in GitHub Desktop.
A new way to extend core validators in Medusa v1.x
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { registerOverriddenValidators } from '@medusajs/medusa' | |
import { type Constructor } from '@medusajs/types' | |
type DecoratorFunction = MethodDecorator | PropertyDecorator | |
type ExtensionDefinition = { | |
[key: string]: DecoratorFunction | DecoratorFunction[] | |
} | |
function extendValidator<Base extends Constructor<any>>( | |
BaseValidator: Base, | |
extension: ExtensionDefinition, | |
): void { | |
const extensionKeys = Object.keys(extension) | |
class ExtendedValidator extends BaseValidator { | |
constructor(...args: any[]) { | |
super(...args) | |
for (let i = 0; i < extensionKeys.length; i++) { | |
this[extensionKeys[i]] = undefined | |
} | |
} | |
} | |
Object.defineProperty(ExtendedValidator, 'name', { value: BaseValidator.name }) | |
const proto = ExtendedValidator.prototype | |
for (let i = 0; i < extensionKeys.length; i++) { | |
const key = extensionKeys[i] | |
const decorators = Array.isArray(extension[key]) ? extension[key] : [extension[key]] | |
for (let j = 0; j < decorators.length; j++) { | |
decorators[j](proto, key, Object.getOwnPropertyDescriptor(proto, key)) | |
} | |
} | |
registerOverriddenValidators(ExtendedValidator) | |
} | |
export { extendValidator } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment