File size: 1,620 Bytes
048b1e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import fs from 'node:fs'
import openapiTS, { astToString } from 'openapi-typescript'
import { factory, SyntaxKind } from 'typescript'

const DATE = factory.createTypeReferenceNode(factory.createIdentifier('Date')) // `Date`
const NULL = factory.createLiteralTypeNode(factory.createNull()) // `null`
const STRING = factory.createKeywordTypeNode(SyntaxKind.StringKeyword) // `string`

const schema = new URL('../../../openapi.cloud.yaml', import.meta.url)

const ast = await openapiTS(schema, {
  defaultNonNullable: false,
  rootTypes: true,
  rootTypesNoSchemaPrefix: true,
  transform(schemaObject, metadata) {
    if (metadata.path === '#/components/schemas/Event') {
      if (
        schemaObject.type === 'string' &&
        !schemaObject.nullable &&
        !['customer-id', 'com.example.someevent'].includes(schemaObject.example)
      ) {
        return {
          questionToken: true,
          schema: STRING,
        }
      }
    }
    if (schemaObject.format === 'date-time') {
      const allowString =
        (metadata.schema &&
          'in' in metadata.schema &&
          metadata.schema.in === 'query') ||
        metadata.path?.includes('/parameters/query')

      // allow string in query parameters
      if (allowString) {
        return schemaObject.nullable
          ? factory.createUnionTypeNode([DATE, NULL, STRING])
          : factory.createUnionTypeNode([DATE, STRING])
      }

      return schemaObject.nullable
        ? factory.createUnionTypeNode([DATE, NULL])
        : DATE
    }
  },
})

const contents = astToString(ast)

fs.writeFileSync('./src/client/schemas.ts', contents)