Skip to content

Commit

Permalink
chore: correct use of mapper
Browse files Browse the repository at this point in the history
  • Loading branch information
stijnvanhulle committed Mar 31, 2024
1 parent 0f08aa4 commit f2b4897
Show file tree
Hide file tree
Showing 21 changed files with 89 additions and 87 deletions.
3 changes: 3 additions & 0 deletions examples/advanced/configs/kubb.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,9 @@ export default defineConfig(async () => {
],
group: { type: 'tag' },
dateType: 'date',
mapper: {
status: `faker.helpers.arrayElement(['working', 'idle']) as any`,
},
}),
createSwaggerMsw({
output: {
Expand Down
2 changes: 1 addition & 1 deletion examples/advanced/src/gen/mocks/createAddPetRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export function createAddPetRequest(override: NonNullable<Partial<AddPetRequest>
category: createCategory(),
photoUrls: faker.helpers.arrayElements([faker.string.alpha()]) as any,
tags: faker.helpers.arrayElements([createTagTag()]) as any,
status: faker.helpers.arrayElement<any>(['available', 'pending', 'sold']),
status: faker.helpers.arrayElement(['working', 'idle']) as any,
},
...override,
}
Expand Down
2 changes: 1 addition & 1 deletion examples/advanced/src/gen/mocks/createOrder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export function createOrder(override: NonNullable<Partial<Order>> = {}): NonNull
orderType: faker.helpers.arrayElement<any>(['foo', 'bar']),
type: faker.string.alpha(),
shipDate: faker.date.anytime(),
status: faker.helpers.arrayElement<any>(['placed', 'approved', 'delivered']),
status: faker.helpers.arrayElement(['working', 'idle']) as any,
http_status: faker.helpers.arrayElement<any>(['ok', 'not_found']),
complete: faker.datatype.boolean(),
},
Expand Down
2 changes: 1 addition & 1 deletion examples/advanced/src/gen/mocks/createPet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export function createPet(override: NonNullable<Partial<Pet>> = {}): NonNullable
category: createCategory(),
photoUrls: faker.helpers.arrayElements([faker.string.alpha()]) as any,
tags: faker.helpers.arrayElements([createTagTag()]) as any,
status: faker.helpers.arrayElement<any>(['available', 'pending', 'sold']),
status: faker.helpers.arrayElement(['working', 'idle']) as any,
},
...override,
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { createPet } from '../createPet'

export function createFindPetsByStatusQueryParams(override: NonNullable<Partial<FindPetsByStatusQueryParams>> = {}): NonNullable<FindPetsByStatusQueryParams> {
return {
...{ status: faker.helpers.arrayElement<any>(['available', 'pending', 'sold']) },
...{ status: faker.helpers.arrayElement(['working', 'idle']) as any },
...override,
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function createUpdatePetWithFormQueryParams(
override: NonNullable<Partial<UpdatePetWithFormQueryParams>> = {},
): NonNullable<UpdatePetWithFormQueryParams> {
return {
...{ name: faker.string.alpha(), status: faker.string.alpha() },
...{ name: faker.string.alpha(), status: faker.helpers.arrayElement(['working', 'idle']) as any },
...override,
}
}
Expand Down
2 changes: 1 addition & 1 deletion examples/faker/kubb.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ module.exports = defineConfig(async () => {
},
},
mapper: {
message: () => 'faker.commerce.productName()',
message: 'faker.commerce.productName()',
},
include: [
{
Expand Down
2 changes: 1 addition & 1 deletion examples/faker/src/gen/customMocks/createApiResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { ApiResponse } from '../models/ApiResponse'

export function createApiResponse(override: NonNullable<Partial<ApiResponse>> = {}): NonNullable<ApiResponse> {
return {
...{ code: faker.number.int(), type: faker.string.alpha(), message: faker.string.alpha() },
...{ code: faker.number.int(), type: faker.string.alpha(), message: faker.commerce.productName() },
...override,
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"lint": "bun biome lint ./packages",
"lint:case": "npx case-police --fix",
"lint:ci": "bun biome lint ./packages",
"lint:fix": "bun biome lint --apply ./packages && bun run lint:case",
"lint:fix": "bun biome lint --apply-unsafe ./packages && bun run lint:case",
"lint:turbo": "turbo run lint",
"release": "changeset publish",
"release:canary": "changeset publish --no-git-tag",
Expand Down
2 changes: 1 addition & 1 deletion packages/core/mocks/hellowWorld.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const hallo = 'world'
export const hallo = 'world'
2 changes: 1 addition & 1 deletion packages/swagger-faker/src/SchemaGenerator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export class SchemaGenerator extends Generator<PluginOptions['resolvedOptions'],
name: resolvedName,
typeName,
description,
mapper: this.options.mapper as typeof fakerKeywordMapper,
mapper: this.options.mapper,
seed: this.options.seed,
})

Expand Down
52 changes: 27 additions & 25 deletions packages/swagger-faker/src/fakerParser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,14 @@ function schemaKeywordsorter(a: Schema, b: Schema) {
return 0
}

function joinItems(items: string[], mapper: typeof fakerKeywordMapper): string {
function joinItems(items: string[]): string {
switch (items.length) {
case 0:
return 'undefined'
case 1:
return items[0]!
default:
return mapper.union(items)
return fakerKeywordMapper.union(items)

Check warning on line 111 in packages/swagger-faker/src/fakerParser.tsx

View check run for this annotation

Codecov / codecov/patch

packages/swagger-faker/src/fakerParser.tsx#L111

Added line #L111 was not covered by tests
}
}

Expand All @@ -119,31 +119,30 @@ type ParserOptions = {

seed?: number | number[]
withOverride?: boolean
mapper?: typeof fakerKeywordMapper
mapper?: Record<string, string>
}

export function parseFakerMeta(parent: Schema | undefined, current: Schema, options: ParserOptions): string | null | undefined {
const mapper = { ...fakerKeywordMapper, ...options.mapper }
const value = mapper[current.keyword as keyof typeof mapper]
const value = fakerKeywordMapper[current.keyword as keyof typeof fakerKeywordMapper]

if (!value) {
return undefined
}

if (isKeyword(current, schemaKeywords.union)) {
return mapper.union(current.args.map((schema) => parseFakerMeta(current, schema, { ...options, withOverride: false })).filter(Boolean))
return fakerKeywordMapper.union(current.args.map((schema) => parseFakerMeta(current, schema, { ...options, withOverride: false })).filter(Boolean))
}

if (isKeyword(current, schemaKeywords.and)) {
return mapper.and(current.args.map((schema) => parseFakerMeta(current, schema, { ...options, withOverride: false })).filter(Boolean))
return fakerKeywordMapper.and(current.args.map((schema) => parseFakerMeta(current, schema, { ...options, withOverride: false })).filter(Boolean))
}

if (isKeyword(current, schemaKeywords.array)) {
return mapper.array(current.args.items.map((schema) => parseFakerMeta(current, schema, { ...options, withOverride: false })).filter(Boolean))
return fakerKeywordMapper.array(current.args.items.map((schema) => parseFakerMeta(current, schema, { ...options, withOverride: false })).filter(Boolean))
}

if (isKeyword(current, schemaKeywords.enum)) {
return mapper.enum(
return fakerKeywordMapper.enum(
current.args.items.map((schema) => {
if (schema.format === 'number') {
return schema.name
Expand Down Expand Up @@ -175,12 +174,16 @@ export function parseFakerMeta(parent: Schema | undefined, current: Schema, opti
const name = item[0]
const schemas = item[1]

// custom mapper(pluginOptions)
if (options.mapper?.[name]) {
return `"${name}": ${options.mapper?.[name]}`
}

Check warning on line 180 in packages/swagger-faker/src/fakerParser.tsx

View check run for this annotation

Codecov / codecov/patch

packages/swagger-faker/src/fakerParser.tsx#L179-L180

Added lines #L179 - L180 were not covered by tests

return `"${name}": ${joinItems(
schemas
.sort(schemaKeywordsorter)
.map((schema) => parseFakerMeta(current, schema, { ...options, withOverride: false }))
.filter(Boolean),
mapper,
)}`
})
.join(',')
Expand All @@ -190,22 +193,22 @@ export function parseFakerMeta(parent: Schema | undefined, current: Schema, opti

if (isKeyword(current, schemaKeywords.tuple)) {
if (Array.isArray(current.args)) {
return mapper.tuple(current.args.map((schema) => parseFakerMeta(current, schema, { ...options, withOverride: false })).filter(Boolean))
return fakerKeywordMapper.tuple(current.args.map((schema) => parseFakerMeta(current, schema, { ...options, withOverride: false })).filter(Boolean))
}

return parseFakerMeta(current, current.args, { ...options, withOverride: false })

Check warning on line 199 in packages/swagger-faker/src/fakerParser.tsx

View check run for this annotation

Codecov / codecov/patch

packages/swagger-faker/src/fakerParser.tsx#L198-L199

Added lines #L198 - L199 were not covered by tests
}

if (isKeyword(current, schemaKeywords.const)) {
if (current.args.format === 'number' && current.args.name !== undefined) {
return mapper.const(current.args.name?.toString())
return fakerKeywordMapper.const(current.args.name?.toString())
}
return mapper.const(transformers.stringify(current.args.value))
return fakerKeywordMapper.const(transformers.stringify(current.args.value))

Check warning on line 206 in packages/swagger-faker/src/fakerParser.tsx

View check run for this annotation

Codecov / codecov/patch

packages/swagger-faker/src/fakerParser.tsx#L203-L206

Added lines #L203 - L206 were not covered by tests
}

if (isKeyword(current, schemaKeywords.matches)) {
if (current.args) {
return mapper.matches(transformers.toRegExpString(current.args))
return fakerKeywordMapper.matches(transformers.toRegExpString(current.args))
}
}

Expand All @@ -218,52 +221,51 @@ export function parseFakerMeta(parent: Schema | undefined, current: Schema, opti
const minSchema = SchemaGenerator.find([parent], schemaKeywords.min)
const maxSchema = SchemaGenerator.find([parent], schemaKeywords.max)

return mapper.string(minSchema?.args, maxSchema?.args)
return fakerKeywordMapper.string(minSchema?.args, maxSchema?.args)
}

return mapper.string()
return fakerKeywordMapper.string()
}

if (isKeyword(current, schemaKeywords.number)) {
if (parent) {
const minSchema = SchemaGenerator.find([parent], schemaKeywords.min)
const maxSchema = SchemaGenerator.find([parent], schemaKeywords.max)

return mapper.number(minSchema?.args, maxSchema?.args)
return fakerKeywordMapper.number(minSchema?.args, maxSchema?.args)
}

return mapper.number()
return fakerKeywordMapper.number()
}

if (isKeyword(current, schemaKeywords.integer)) {
if (parent) {
const minSchema = SchemaGenerator.find([parent], schemaKeywords.min)
const maxSchema = SchemaGenerator.find([parent], schemaKeywords.max)

return mapper.integer(minSchema?.args, maxSchema?.args)
return fakerKeywordMapper.integer(minSchema?.args, maxSchema?.args)
}

return mapper.integer()
return fakerKeywordMapper.integer()

Check warning on line 249 in packages/swagger-faker/src/fakerParser.tsx

View check run for this annotation

Codecov / codecov/patch

packages/swagger-faker/src/fakerParser.tsx#L242-L249

Added lines #L242 - L249 were not covered by tests
}

if (current.keyword in mapper && 'args' in current) {
const value = mapper[current.keyword as keyof typeof mapper] as (typeof fakerKeywordMapper)['const']
if (current.keyword in fakerKeywordMapper && 'args' in current) {
const value = fakerKeywordMapper[current.keyword as keyof typeof fakerKeywordMapper] as (typeof fakerKeywordMapper)['const']

const options = JSON.stringify((current as SchemaKeywordBase<unknown>).args)

return value(options)

Check warning on line 257 in packages/swagger-faker/src/fakerParser.tsx

View check run for this annotation

Codecov / codecov/patch

packages/swagger-faker/src/fakerParser.tsx#L253-L257

Added lines #L253 - L257 were not covered by tests
}

if (current.keyword in mapper) {
if (current.keyword in fakerKeywordMapper) {
return value()
}

return undefined
}

export function fakerParser(schemas: Schema[], options: ParserOptions): string {
const mapper = { ...fakerKeywordMapper, ...options.mapper }
const fakerText = joinItems(schemas.map((schema) => parseFakerMeta(undefined, schema, { ...options, withOverride: true })).filter(Boolean), mapper)
const fakerText = joinItems(schemas.map((schema) => parseFakerMeta(undefined, schema, { ...options, withOverride: true })).filter(Boolean))

let fakerDefaultOverride: '' | '[]' | '{}' = ''
let fakerTextWithOverride = fakerText
Expand Down
5 changes: 1 addition & 4 deletions packages/swagger-faker/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,7 @@ export const definePlugin = createPlugin<PluginOptions>((options) => {
dateType,
seed,
unknownType,
mapper: {
...fakerKeywordMapper,
...mapper,
},
mapper,
},
pre: [swaggerPluginName, swaggerTypeScriptPluginName],
resolvePath(baseName, pathMode, options) {
Expand Down
4 changes: 2 additions & 2 deletions packages/swagger-faker/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export type Options = {
*/
schema?: (schema: OasTypes.SchemaObject | undefined, baseName?: string) => Schema[] | undefined
}
mapper?: Partial<SchemaMapper>
mapper?: Record<string, string>
/**
* The use of Seed is intended to allow for consistent values in a test.
*/
Expand All @@ -94,7 +94,7 @@ type ResolvedOptions = {
unknownType: NonNullable<Options['unknownType']>
transformers: NonNullable<Options['transformers']>
seed: NonNullable<Options['seed']> | undefined
mapper: NonNullable<SchemaMapper<string | null | undefined>>
mapper: Record<string, string>
}

export type FileMeta = {
Expand Down
23 changes: 11 additions & 12 deletions packages/swagger-ts/src/typeParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,47 +121,46 @@ type ParserOptions = {
*/
enumType: 'enum' | 'asConst' | 'asPascalConst' | 'constEnum' | 'literal'
keysToOmit?: string[]
mapper?: typeof typeKeywordMapper
mapper?: SchemaMapper
}

export function parseTypeMeta(parent: Schema | undefined, current: Schema, options: ParserOptions): ts.Node | null | undefined {
const mapper = { ...typeKeywordMapper, ...options.mapper }
const value = mapper[current.keyword as keyof typeof mapper]
const value = typeKeywordMapper[current.keyword as keyof typeof typeKeywordMapper]

if (!value) {
return undefined
}

if (isKeyword(current, schemaKeywords.union)) {
return mapper.union(current.args.map((schema) => parseTypeMeta(current, schema, options)).filter(Boolean) as ts.TypeNode[])
return typeKeywordMapper.union(current.args.map((schema) => parseTypeMeta(current, schema, options)).filter(Boolean) as ts.TypeNode[])
}

if (isKeyword(current, schemaKeywords.and)) {
return mapper.and(current.args.map((schema) => parseTypeMeta(current, schema, options)).filter(Boolean) as ts.TypeNode[])
return typeKeywordMapper.and(current.args.map((schema) => parseTypeMeta(current, schema, options)).filter(Boolean) as ts.TypeNode[])
}

if (isKeyword(current, schemaKeywords.array)) {
return mapper.array(current.args.items.map((schema) => parseTypeMeta(current, schema, options)).filter(Boolean) as ts.TypeNode[])
return typeKeywordMapper.array(current.args.items.map((schema) => parseTypeMeta(current, schema, options)).filter(Boolean) as ts.TypeNode[])
}

if (isKeyword(current, schemaKeywords.enum)) {
return mapper.enum(current.args.typeName)
return typeKeywordMapper.enum(current.args.typeName)
}

if (isKeyword(current, schemaKeywords.ref)) {
return mapper.ref(current.args.name)
return typeKeywordMapper.ref(current.args.name)
}

if (isKeyword(current, schemaKeywords.blob)) {
return value()
}

if (isKeyword(current, schemaKeywords.tuple)) {
return mapper.tuple(current.args.map((schema) => parseTypeMeta(current, schema, options)).filter(Boolean) as ts.TypeNode[])
return typeKeywordMapper.tuple(current.args.map((schema) => parseTypeMeta(current, schema, options)).filter(Boolean) as ts.TypeNode[])
}

if (isKeyword(current, schemaKeywords.const)) {
return mapper.const(current.args.name, current.args.format)
return typeKeywordMapper.const(current.args.name, current.args.format)
}

if (isKeyword(current, schemaKeywords.object)) {
Expand Down Expand Up @@ -233,10 +232,10 @@ export function parseTypeMeta(parent: Schema | undefined, current: Schema, optio
)
: undefined

return mapper.object([...properties, additionalProperties].filter(Boolean))
return typeKeywordMapper.object([...properties, additionalProperties].filter(Boolean))
}

if (current.keyword in mapper) {
if (current.keyword in typeKeywordMapper) {
return value()
}

Expand Down
2 changes: 1 addition & 1 deletion packages/swagger-zod/src/SchemaGenerator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export class SchemaGenerator extends Generator<PluginOptions['resolvedOptions'],
type: 'function',
}),
description,
mapper: this.options.mapper as typeof zodKeywordMapper,
mapper: this.options.mapper,
typeName: withTypeAnnotation ? typeName : undefined,
})

Expand Down
5 changes: 1 addition & 4 deletions packages/swagger-zod/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,7 @@ export const definePlugin = createPlugin<PluginOptions>((options) => {
typed,
dateType,
unknownType,
mapper: {
...zodKeywordMapper,
...mapper,
},
mapper,
templates: {
operations: Operations.templates,
...templates,
Expand Down
4 changes: 2 additions & 2 deletions packages/swagger-zod/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export type Options = {
*/
name?: (name: ResolveNameParams['name'], type?: ResolveNameParams['type']) => string
}
mapper?: Partial<SchemaMapper>
mapper?: Record<string, string>
/**
* Make it possible to override one of the templates
*/
Expand Down Expand Up @@ -99,7 +99,7 @@ type ResolvedOptions = {
unknownType: NonNullable<Options['unknownType']>
typed: NonNullable<Options['typed']>
templates: NonNullable<Templates>
mapper: NonNullable<SchemaMapper>
mapper: Record<string, string>
}

export type FileMeta = {
Expand Down
Loading

0 comments on commit f2b4897

Please sign in to comment.