source: trip-planner-front/node_modules/ajv-formats/src/index.ts@ 6a3a178

Last change on this file since 6a3a178 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.8 KB
Line 
1import {
2 DefinedFormats,
3 FormatMode,
4 FormatName,
5 formatNames,
6 fastFormats,
7 fullFormats,
8} from "./formats"
9import formatLimit from "./limit"
10import type Ajv from "ajv"
11import type {Plugin, Format} from "ajv"
12import {_, Name} from "ajv/dist/compile/codegen"
13
14export {FormatMode, FormatName} from "./formats"
15export {LimitFormatError} from "./limit"
16export interface FormatOptions {
17 mode?: FormatMode
18 formats?: FormatName[]
19 keywords?: boolean
20}
21
22export type FormatsPluginOptions = FormatName[] | FormatOptions
23
24export interface FormatsPlugin extends Plugin<FormatsPluginOptions> {
25 get: (format: FormatName, mode?: FormatMode) => Format
26}
27
28const fullName = new Name("fullFormats")
29const fastName = new Name("fastFormats")
30
31const formatsPlugin: FormatsPlugin = (
32 ajv: Ajv,
33 opts: FormatsPluginOptions = {keywords: true}
34): Ajv => {
35 if (Array.isArray(opts)) {
36 addFormats(ajv, opts, fullFormats, fullName)
37 return ajv
38 }
39 const [formats, exportName] =
40 opts.mode === "fast" ? [fastFormats, fastName] : [fullFormats, fullName]
41 const list = opts.formats || formatNames
42 addFormats(ajv, list, formats, exportName)
43 if (opts.keywords) formatLimit(ajv)
44 return ajv
45}
46
47formatsPlugin.get = (name: FormatName, mode: FormatMode = "full"): Format => {
48 const formats = mode === "fast" ? fastFormats : fullFormats
49 const f = formats[name]
50 if (!f) throw new Error(`Unknown format "${name}"`)
51 return f
52}
53
54function addFormats(ajv: Ajv, list: FormatName[], fs: DefinedFormats, exportName: Name): void {
55 ajv.opts.code.formats ??= _`require("ajv-formats/dist/formats").${exportName}`
56 for (const f of list) ajv.addFormat(f, fs[f])
57}
58
59module.exports = exports = formatsPlugin
60Object.defineProperty(exports, "__esModule", {value: true})
61
62export default formatsPlugin
Note: See TracBrowser for help on using the repository browser.