index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { dirname } from "node:path";
  2. import { fileURLToPath } from "node:url";
  3. import $RefParser from "@apidevtools/json-schema-ref-parser";
  4. const __filename = fileURLToPath(import.meta.url);
  5. const __dirname = dirname(__filename);
  6. let compiledSchema = null;
  7. /**
  8. * Compiles the schema, by dereferencing it, only once
  9. * and returns the memory cached value
  10. */
  11. const getCompiledSchema = async () => {
  12. if (compiledSchema === null) {
  13. compiledSchema = await $RefParser.dereference(`${__dirname}/swagger.json`, {
  14. mutateInputSchema: false,
  15. });
  16. }
  17. return compiledSchema;
  18. };
  19. /**
  20. * Scans the schema for the validation schema for the given path and method
  21. * and returns it.
  22. *
  23. * @param {string} path
  24. * @param {string} method
  25. * @returns string|null
  26. */
  27. const getValidationSchema = (path, method) => {
  28. if (
  29. compiledSchema !== null &&
  30. typeof compiledSchema.paths[path] !== "undefined" &&
  31. typeof compiledSchema.paths[path][method] !== "undefined" &&
  32. typeof compiledSchema.paths[path][method].requestBody !== "undefined" &&
  33. typeof compiledSchema.paths[path][method].requestBody.content !== "undefined" &&
  34. typeof compiledSchema.paths[path][method].requestBody.content["application/json"] !== "undefined" &&
  35. typeof compiledSchema.paths[path][method].requestBody.content["application/json"].schema !== "undefined"
  36. ) {
  37. return compiledSchema.paths[path][method].requestBody.content["application/json"].schema;
  38. }
  39. return null;
  40. };
  41. export { getCompiledSchema, getValidationSchema };