Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions packages/openapi-generator/src/codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,8 @@ function parseObjectExpression(
} else if (
property.key.type !== 'Identifier' &&
property.key.type !== 'StringLiteral' &&
property.key.type !== 'NumericLiteral'
property.key.type !== 'NumericLiteral' &&
property.key.type !== 'Computed'
) {
return errorLeft(`Unimplemented property key type ${property.key.type}`);
}
Expand All @@ -235,7 +236,41 @@ function parseObjectExpression(
commentEndIdx,
);
commentStartIdx = (property.value as swc.HasSpan).span.end;
const name = property.key.value;

let name: string = '';
if (property.key.type === 'Computed') {
if (property.key.expression.type !== 'Identifier') {
return errorLeft(
`Unimplemented computed property value type ${property.value.type}`,
);
}

const initE = findSymbolInitializer(
project,
source,
property.key.expression.value,
);
if (E.isLeft(initE)) {
return initE;
}
const [newSourceFile, init] = initE.right;
const valueE = parsePlainInitializer(project, newSourceFile, init);
if (E.isLeft(valueE)) {
return valueE;
}
const schema = valueE.right;
if (
(schema.type === 'string' || schema.type === 'number') &&
schema.enum !== undefined
) {
name = String(schema.enum[0]);
} else {
return errorLeft('Computed property must be string or number literal');
}
} else {
name = String(property.key.value);
}

const valueE = parsePlainInitializer(project, source, property.value);
if (E.isLeft(valueE)) {
return valueE;
Expand Down
26 changes: 24 additions & 2 deletions packages/openapi-generator/test/codec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -554,7 +554,7 @@ testCase(
DECLARATION_COMMENT_WITHOUT_LINE_BREAK,
{
FOO: {
type: 'number',
type: 'number',
primitive: true,
comment: {
description: 'Test codec',
Expand Down Expand Up @@ -682,7 +682,7 @@ testCase('second property comment is parsed', SECOND_PROPERTY_COMMENT, {
properties: {
foo: { type: 'number', primitive: true },
bar: {
type: 'string',
type: 'string',
primitive: true,
comment: {
description: 'this is a comment',
Expand Down Expand Up @@ -848,3 +848,25 @@ testCase('object assign is parsed', OBJECT_ASSIGN, {
required: ['foo', 'bar'],
},
});

const COMPUTED_PROPERTY = `
import * as t from 'io-ts';
const key = 'foo';
export const FOO = t.type({
[key]: t.number,
});
`;

testCase('computed property is parsed', COMPUTED_PROPERTY, {
FOO: {
type: 'object',
properties: {
foo: { type: 'number', primitive: true },
},
required: ['foo'],
},
key: {
type: 'string',
enum: ['foo'],
}
});