Skip to content

Commit 95a569b

Browse files
committed
fix typescript template identifiers with dash
1 parent 7d12fe1 commit 95a569b

File tree

2 files changed

+65
-2
lines changed

2 files changed

+65
-2
lines changed

src/generators/TypescriptInterfaceGenerator.js

+7-2
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,19 @@ export default class TypescriptInterfaceGenerator extends BaseGenerator {
1818
const dest = `${dir}/interfaces`;
1919
const { fields, imports } = this.parseFields(resource);
2020

21+
const normalizeJs = (name) => name.replace(/-/g, "_");
22+
2123
this.createDir(dest, false);
2224
this.createFile(
2325
"interface.ts",
2426
`${dest}/${resource.title.toLowerCase()}.ts`,
2527
{
26-
fields,
28+
fields: fields.map((f) => ({
29+
...f,
30+
name: normalizeJs(f.name),
31+
})),
2732
imports,
28-
name: resource.title,
33+
name: normalizeJs(resource.title),
2934
}
3035
);
3136
}

src/generators/TypescriptInterfaceGenerator.test.js

+58
Original file line numberDiff line numberDiff line change
@@ -169,3 +169,61 @@ test("Generate a typescript interface with an explicit id field in the readableF
169169

170170
tmpobj.removeCallback();
171171
});
172+
173+
test("Generate a typescript interface with normalized JS identifiers", () => {
174+
const generator = new TypescriptInterfaceGenerator({
175+
templateDirectory: `${__dirname}/../../templates`,
176+
});
177+
const tmpobj = tmp.dirSync({ unsafeCleanup: true });
178+
179+
const resource = new Resource("abc", "http://example.com/foos", {
180+
id: "foo",
181+
title: "Foo-foo",
182+
readableFields: [
183+
new Field("bar-bar", {
184+
id: "http://schema.org/url",
185+
range: "http://www.w3.org/2001/XMLSchema#string",
186+
reference: null,
187+
required: true,
188+
description: "An URL",
189+
}),
190+
new Field("id", {
191+
id: "http://schema.org/url",
192+
range: "http://www.w3.org/2001/XMLSchema#string",
193+
reference: null,
194+
required: false,
195+
description: "Id",
196+
}),
197+
],
198+
writableFields: [
199+
new Field("foo-foo", {
200+
id: "http://schema.org/url",
201+
range: "http://www.w3.org/2001/XMLSchema#datetime",
202+
reference: null,
203+
required: true,
204+
description: "An URL",
205+
}),
206+
],
207+
});
208+
const api = new Api("http://example.com", {
209+
entrypoint: "http://example.com:8080",
210+
title: "My API",
211+
resources: [resource],
212+
});
213+
generator.generate(api, resource, tmpobj.name);
214+
215+
expect(fs.existsSync(tmpobj.name + "/interfaces/foo-foo.ts")).toBe(true);
216+
217+
const res = `export interface Foo_foo {
218+
"@id"?: string;
219+
foo_foo: any;
220+
readonly bar_bar: string;
221+
readonly id?: string;
222+
}
223+
`;
224+
expect(
225+
fs.readFileSync(tmpobj.name + "/interfaces/foo-foo.ts").toString()
226+
).toEqual(res);
227+
228+
tmpobj.removeCallback();
229+
});

0 commit comments

Comments
 (0)