-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
57 lines (46 loc) · 1.67 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { docSchemas } from '@comapeo/schema'
import { JSONSchemaFaker, createFakerSchema } from './lib/faker.js'
import { extractSchemaVersion, isValidSchemaName } from './lib/schema.js'
/** @typedef {import('@comapeo/schema/dist/types.js').SchemaName} SchemaName */
export function listSchemas() {
/** @type {{[name: string]: Array<string>}} */
const result = {}
for (const [schemaName, schema] of Object.entries(docSchemas)) {
result[schemaName] = [extractSchemaVersion(schema.$id)]
}
return result
}
/** @type {Map<SchemaName, ReturnType<typeof createFakerSchema>>} schemaCache */
const fakerSchemaCache = new Map()
/**
* @param {SchemaName} schemaName
*/
function getFakerSchema(schemaName) {
const cached = fakerSchemaCache.get(schemaName)
if (cached) return cached
const targetSchema = docSchemas[schemaName]
const result = createFakerSchema(targetSchema)
fakerSchemaCache.set(schemaName, result)
return result
}
/**
* @template {SchemaName} TSchemaName
* @param {TSchemaName} schemaName
* @param {{version?: string, count?: number}} [options]
* @returns {Array<Extract<import('@comapeo/schema').MapeoDoc, { schemaName: TSchemaName }>>}
*/
export function generate(schemaName, { count } = {}) {
isValidSchemaName(schemaName)
const schema = getFakerSchema(schemaName)
const numberToGenerate = count || 1
/** @type {Array<Extract<import('@comapeo/schema').MapeoDoc, { schemaName: TSchemaName }>>} */
const result = []
for (let i = 0; i < numberToGenerate; i++) {
result.push(
/** @type {Extract<import('@comapeo/schema').MapeoDoc, { schemaName: TSchemaName }>} */ (
JSONSchemaFaker.generate(schema)
),
)
}
return result
}