cfworker-provider.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * Cloudflare Worker-compatible JSON Schema validator provider
  3. *
  4. * This provider uses @cfworker/json-schema for validation without code generation,
  5. * making it compatible with edge runtimes like Cloudflare Workers that restrict
  6. * eval and new Function.
  7. */
  8. import { Validator } from '@cfworker/json-schema';
  9. /**
  10. *
  11. * @example
  12. * ```typescript
  13. * // Use with default configuration (2020-12, shortcircuit)
  14. * const validator = new CfWorkerJsonSchemaValidator();
  15. *
  16. * // Use with custom configuration
  17. * const validator = new CfWorkerJsonSchemaValidator({
  18. * draft: '2020-12',
  19. * shortcircuit: false // Report all errors
  20. * });
  21. * ```
  22. */
  23. export class CfWorkerJsonSchemaValidator {
  24. /**
  25. * Create a validator
  26. *
  27. * @param options - Configuration options
  28. * @param options.shortcircuit - If true, stop validation after first error (default: true)
  29. * @param options.draft - JSON Schema draft version to use (default: '2020-12')
  30. */
  31. constructor(options) {
  32. this.shortcircuit = options?.shortcircuit ?? true;
  33. this.draft = options?.draft ?? '2020-12';
  34. }
  35. /**
  36. * Create a validator for the given JSON Schema
  37. *
  38. * Unlike AJV, this validator is not cached internally
  39. *
  40. * @param schema - Standard JSON Schema object
  41. * @returns A validator function that validates input data
  42. */
  43. getValidator(schema) {
  44. // Cast to the cfworker Schema type - our JsonSchemaType is structurally compatible
  45. const validator = new Validator(schema, this.draft, this.shortcircuit);
  46. return (input) => {
  47. const result = validator.validate(input);
  48. if (result.valid) {
  49. return {
  50. valid: true,
  51. data: input,
  52. errorMessage: undefined
  53. };
  54. }
  55. else {
  56. return {
  57. valid: false,
  58. data: undefined,
  59. errorMessage: result.errors.map(err => `${err.instanceLocation}: ${err.error}`).join('; ')
  60. };
  61. }
  62. };
  63. }
  64. }
  65. //# sourceMappingURL=cfworker-provider.js.map