-
Notifications
You must be signed in to change notification settings - Fork 0
/
directus-types-gen.js
93 lines (76 loc) · 2.8 KB
/
directus-types-gen.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import 'dotenv/config'
import { writeFile } from 'node:fs/promises'
import Pino from 'pino'
import openapiTS, { astToString } from 'openapi-typescript'
const logger = Pino({
level: 'info'
})
// SEE: https://github.com/elierotenberg/directus-typescript-gen
async function generate() {
const resp = await fetch(
new URL('/server/specs/oas', process.env.DIRECTUS_URL + ''),
{
headers: {
Authorization: `Bearer ${process.env.DIRECTUS_STATIC_TOKEN}`,
'Content-Type': 'application/json'
}
}
)
if (!resp.ok) {
throw new Error(`Non-success status returned: ${resp.status}`)
}
const spec = await resp.json()
const ast = await openapiTS(spec)
const source = astToString(ast)
//
// NOTE: OpenAPI types only -- manually define DirectusSchema
//
// source += `\n\nexport type GeneratedSchema = {\n`
// if (spec.paths) {
// for (const [path, pathItem] of Object.entries(spec.paths)) {
// const collectionPathPattern = /^\/items\/(?<collection>[a-zA-Z0-9_]+)$/
// const collection =
// collectionPathPattern.exec(path)?.groups?.[`collection`]
// if (typeof collection !== `string` || collection.length === 0) {
// continue
// }
// if (
// `get` in pathItem &&
// `responses` in pathItem.get &&
// `200` in pathItem.get.responses &&
// `content` in pathItem.get.responses[`200`] &&
// `application/json` in pathItem.get.responses[`200`].content &&
// `schema` in pathItem.get.responses[`200`].content[`application/json`] &&
// `properties` in
// pathItem.get.responses[`200`].content[`application/json`].schema &&
// `data` in
// pathItem.get.responses[`200`].content[`application/json`].schema
// .properties &&
// `items` in
// pathItem.get.responses[`200`].content[`application/json`].schema
// .properties[`data`] &&
// `$ref` in
// pathItem.get.responses[`200`].content[`application/json`].schema
// .properties[`data`].items
// ) {
// const $ref =
// pathItem.get.responses[`200`].content[`application/json`].schema
// .properties[`data`].items.$ref
// const refPattern = /^#\/components\/schemas\/(?<ref>[a-zA-Z0-9_]+)$/
// const ref = refPattern.exec($ref)?.groups?.[`ref`]
// if (typeof ref !== `string` || ref.length === 0) {
// continue
// }
// source += ` ${collection}: components["schemas"]["${ref}"][];\n`
// }
// }
// }
// source += `};\n`
logger.info('Writing source file')
await writeFile(`packages/common/src/types/directus.d.ts`, source)
logger.info('Generate done!')
}
logger.info('Generating Directus types...')
generate().catch(err => {
console.log(err)
})