Skip to content

Commit b8829e0

Browse files
authored
feat: format generated code using Prettier (#259)
1 parent 9fcc561 commit b8829e0

File tree

13 files changed

+146
-127
lines changed

13 files changed

+146
-127
lines changed

.travis.yml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ script:
1212
- yarn test
1313
- yarn lint
1414
- yarn test-gen
15-
#- yarn test-gen-cs
1615
- yarn test-gen-env
1716
- yarn check
1817

package.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@
3232
"husky": "^4.3.6",
3333
"jest": "^26.6.3",
3434
"lint-staged": "^10.5.3",
35-
"prettier": "^2.2.1",
3635
"tmp": "^0.2.1"
3736
},
3837
"dependencies": {
@@ -44,6 +43,7 @@
4443
"handlebars-helpers": "^0.10.0",
4544
"isomorphic-fetch": "^3.0.0",
4645
"mkdirp": "^1.0.4",
46+
"prettier": "^2.2.1",
4747
"sprintf-js": "^1.1.1"
4848
},
4949
"scripts": {
@@ -54,7 +54,6 @@
5454
"build": "babel src -d lib --ignore '*.test.js'",
5555
"watch": "babel --watch src -d lib --ignore '*.test.js'",
5656
"test-gen": "rm -rf ./tmp && yarn build && ./lib/index.js https://demo.api-platform.com ./tmp/react -g react && ./lib/index.js https://demo.api-platform.com ./tmp/react-native -g react-native && ./lib/index.js https://demo.api-platform.com ./tmp/vue -g vue",
57-
"test-gen-cs": "./node_modules/.bin/prettier --single-quote -l \"./tmp/react/**/*.{js,jsx,ts,tsx,json,css,scss,md}\"",
5857
"test-gen-swagger": "rm -rf ./tmp && yarn build && ./lib/index.js https://demo.api-platform.com/docs.json ./tmp/react -f swagger && ./lib/index.js https://demo.api-platform.com/docs.json ./tmp/react-native -g react-native -f swagger && ./lib/index.js https://demo.api-platform.com/docs.json ./tmp/vue -g vue -f swagger",
5958
"test-gen-env": "rm -rf ./tmp && yarn build && API_PLATFORM_CLIENT_GENERATOR_ENTRYPOINT=https://demo.api-platform.com API_PLATFORM_CLIENT_GENERATOR_OUTPUT=./tmp ./lib/index.js"
6059
},

src/generators/BaseGenerator.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import fs from "fs";
33
import handlebars from "handlebars";
44
import mkdirp from "mkdirp";
55
import { sprintf } from "sprintf-js";
6+
import prettier from "prettier";
67

78
export default class {
89
templates = {};
@@ -53,8 +54,16 @@ export default class {
5354
return;
5455
}
5556

57+
// Format the generated code using Prettier
58+
let content = this.templates[template](context);
59+
if (template.endsWith(".js")) {
60+
content = prettier.format(content, { parser: "babel" });
61+
} else if (template.endsWith(".ts") || template.endsWith(".tsx")) {
62+
content = prettier.format(content, { parser: "babel-ts" });
63+
}
64+
5665
if (!fs.existsSync(dest)) {
57-
fs.writeFileSync(dest, this.templates[template](context));
66+
fs.writeFileSync(dest, content);
5867

5968
return;
6069
}

src/generators/NextGenerator.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,12 +62,11 @@ export default class NextGenerator extends BaseGenerator {
6262
`${dir}/config`,
6363
`${dir}/error`,
6464
`${dir}/types`,
65-
`${dir}/pages`,
6665
`${dir}/pages/${context.lc}s/[id]`,
6766
`${dir}/utils`,
6867
].forEach((dir) => this.createDir(dir, false));
6968

70-
// copy with patterned name
69+
// Copy with patterned name
7170
this.createDir(`${dir}/components/${context.lc}`);
7271
this.createDir(`${dir}/pages/${context.lc}s`);
7372
this.createDir(`${dir}/pages/${context.lc}s/[id]`);

src/generators/TypescriptInterfaceGenerator.test.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ test("Generate a typescript interface", () => {
4949
expect(fs.existsSync(tmpobj.name + "/interfaces/foo.ts")).toBe(true);
5050

5151
const res = `export interface Foo {
52-
'@id'?: string;
52+
"@id"?: string;
5353
foo: any;
5454
foobar?: string[];
5555
readonly bar: string;
@@ -100,7 +100,7 @@ test("Generate a typescript interface without references to other interfaces", (
100100
expect(fs.existsSync(tmpobj.name + "/interfaces/foo.ts")).toBe(true);
101101

102102
const res = `export interface Foo {
103-
'@id'?: string;
103+
"@id"?: string;
104104
foo: any;
105105
readonly bar: string;
106106
}
@@ -157,7 +157,7 @@ test("Generate a typescript interface with an explicit id field in the readableF
157157
expect(fs.existsSync(tmpobj.name + "/interfaces/foo.ts")).toBe(true);
158158

159159
const res = `export interface Foo {
160-
'@id'?: string;
160+
"@id"?: string;
161161
foo: any;
162162
readonly bar: string;
163163
readonly id?: string;
Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,40 @@
1-
import Link from 'next/link';
2-
import { Fragment, FunctionComponent } from 'react';
1+
import Link from "next/link";
2+
import { Fragment, FunctionComponent } from "react";
33

44
interface Props {
5-
items: string|string[];
5+
items: string | string[];
66
type: string;
7-
useIcon?: boolean
7+
useIcon?: boolean;
88
}
9-
export const ReferenceLinks: FunctionComponent<Props> = ({items, type, useIcon = false}) => {
9+
export const ReferenceLinks: FunctionComponent<Props> = ({
10+
items,
11+
type,
12+
useIcon = false,
13+
}) => {
1014
if (Array.isArray(items)) {
1115
return (
1216
<Fragment>
1317
{items.map((item, index) => (
14-
<div key={index}><ReferenceLinks items={item} type={type}/></div>
18+
<div key={index}>
19+
<ReferenceLinks items={item} type={type} />
20+
</div>
1521
))}
1622
</Fragment>
1723
);
1824
}
1925

2026
return (
21-
<Link href={items}><a>
22-
{useIcon ? (
23-
<Fragment>
24-
<span className="fa fa-search" aria-hidden="true" />
25-
<span className="sr-only">Show</span>
26-
</Fragment>
27-
) : items}
28-
</a></Link>
29-
)
27+
<Link href={items}>
28+
<a>
29+
{useIcon ? (
30+
<Fragment>
31+
<span className="fa fa-search" aria-hidden="true" />
32+
<span className="sr-only">Show</span>
33+
</Fragment>
34+
) : (
35+
items
36+
)}
37+
</a>
38+
</Link>
39+
);
3040
};

templates/next/components/foo/Form.tsx

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ export const Form: FunctionComponent<Props> = ({ {{{lc}}} }) => {
1515
const handleDelete = () => {
1616
if (window.confirm("Are you sure you want to delete this item?")) {
1717
try {
18-
fetch({ {{{lc}}}['@id'] }, { method: "DELETE" });
18+
fetch({{{lc}}}['@id'], { method: "DELETE" });
1919
router.push("/{{{name}}}");
2020
} catch (error) {
2121
setError("Error when deleting the resource.");
@@ -31,22 +31,20 @@ export const Form: FunctionComponent<Props> = ({ {{{lc}}} }) => {
3131
initialValues={ {{{lc}}} ?? new{{{lc}}}() }
3232
validate={(values) => {
3333
const errors = {};
34-
//set your validation logic here
34+
// add your validation logic here
3535
return errors;
3636
}}
3737
onSubmit={(values, { setSubmitting, setStatus }) => {
3838
const isCreation = !{{{lc}}}["@id"];
3939
try {
40-
fetch(isCreation ? "/{{{name}}}" : {{{lc}}}["@id"],
41-
{
42-
method: isCreation ? "POST" : "PATCH",
43-
body: JSON.stringify(values),
44-
}
45-
);
40+
fetch(isCreation ? "/{{{name}}}" : {{{lc}}}["@id"], {
41+
method: isCreation ? "POST" : "PATCH",
42+
body: JSON.stringify(values),
43+
});
4644
setStatus({
47-
isValid: true,
48-
msg: `Element ${isCreation ? 'created': 'updated'}.`,
49-
});
45+
isValid: true,
46+
msg: `Element ${isCreation ? 'created': 'updated'}.`,
47+
});
5048
router.push("/{{{name}}}");
5149
} catch (error) {
5250
setStatus({
@@ -67,40 +65,40 @@ export const Form: FunctionComponent<Props> = ({ {{{lc}}} }) => {
6765
}) => (
6866
<form onSubmit={handleSubmit}>
6967
{{#each fields}}
70-
<div className='form-group'>
68+
<div className="form-group">
7169
<label>{{name}}</label>
7270
<input
73-
className='form-control'
74-
type='text'
75-
name='isbn'
71+
className="form-control"
72+
type="text"
73+
name="isbn"
7674
onChange={handleChange}
7775
onBlur={handleBlur}
7876
value={ values.{{name}} }
7977
required
8078
/>
8179
</div>
82-
{/* {errors.{{name}} && touched.{{name}} && errors.{{name}} */}
80+
{ errors.{{name}} && touched.{{name}} && errors.{{name}} }
8381
{{/each}}
8482
{status && status.msg && (
8583
<div
8684
className={`alert ${
8785
status.isValid ? "alert-success" : "alert-danger"
8886
}`}
89-
role='alert'
87+
role="alert"
9088
>
9189
{status.msg}
9290
</div>
9391
)}
9492

9593
{error && (
96-
<div className='alert alert-danger' role='alert'>
94+
<div className="alert alert-danger" role="alert">
9795
{error}
9896
</div>
9997
)}
10098

10199
<button
102-
type='submit'
103-
className='btn btn-success'
100+
type="submit"
101+
className="btn btn-success"
104102
disabled={isSubmitting}
105103
>
106104
Submit
@@ -109,10 +107,10 @@ export const Form: FunctionComponent<Props> = ({ {{{lc}}} }) => {
109107
)}
110108
</Formik>
111109
<Link href="/{{{name}}}">
112-
<a className='btn btn-primary'>Back to list</a>
110+
<a className="btn btn-primary">Back to list</a>
113111
</Link>
114112
{ {{{lc}}} && (
115-
<button className='btn btn-danger' onClick={handleDelete}>
113+
<button className="btn btn-danger" onClick={handleDelete}>
116114
<a>Delete</a>
117115
</button>
118116
)}

templates/next/components/foo/List.tsx

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,11 @@ export const List: FunctionComponent<Props> = ({ {{{name}}} }) => (
2626
{ {{{name}}} && ({{{name}}}.length !== 0) && {{{name}}}.map( ( {{{lc}}} ) => (
2727
<tr key={ {{{lc}}}['@id'] }>
2828
<th scope="row"><ReferenceLinks items={ {{{lc}}}['@id'] } type="{{{lc}}}" /></th>
29-
{{#each fields}}
30-
<td>{{#if reference}}<ReferenceLinks items={ {{{../lc}}}['{{{name}}}'] } type="{{{reference.title}}}" />{{else}}{ {{{../lc}}}['{{{name}}}'] }{{/if}}</td>
31-
{{/each}}
32-
<td><ReferenceLinks items={ {{{lc}}}['@id'] } type="{{{lc}}}" useIcon={true} /></td>
33-
</tr>
29+
{{#each fields}}
30+
<td>{{#if reference}}<ReferenceLinks items={ {{{../lc}}}['{{{name}}}'] } type="{{{reference.title}}}" />{{else}}{ {{{../lc}}}['{{{name}}}'] }{{/if}}</td>
31+
{{/each}}
32+
<td><ReferenceLinks items={ {{{lc}}}['@id'] } type="{{{lc}}}" useIcon={true} /></td>
33+
</tr>
3434
))}
3535
</tbody>
3636
</table>

templates/next/components/foo/Show.tsx

Lines changed: 37 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -15,46 +15,48 @@ export const Show: FunctionComponent<Props> = ({ {{{lc}}} }) => {
1515
const handleDelete = () => {
1616
if (window.confirm("Are you sure you want to delete this item?")) {
1717
try {
18-
fetch({ {{{lc}}}["@id"] }, { method: "DELETE" });
18+
fetch({{{lc}}}["@id"], { method: "DELETE" });
1919
router.push("/{{{name}}}");
2020
} catch (error) {
2121
setError("Error when deleting the resource.");
2222
console.error(error);
2323
}
2424
}
25-
};
26-
return(
27-
<div>
28-
<h1>Show { {{{lc}}}['@id'] }</h1>
29-
<table className="table table-responsive table-striped table-hover">
30-
<thead>
31-
<tr>
32-
<th>Field</th>
33-
<th>Value</th>
34-
</tr>
35-
</thead>
36-
<tbody>
37-
{{#each fields}}
25+
};
26+
27+
return (
28+
<div>
29+
<h1>Show { {{{lc}}}['@id'] }</h1>
30+
<table className="table table-responsive table-striped table-hover">
31+
<thead>
3832
<tr>
39-
<th scope="row">{{name}}</th>
40-
<td>{{#if reference}}<ReferenceLinks items={ {{{../lc}}}['{{{name}}}'] } type="{{{reference.title}}}" />{{else}}{ {{{../lc}}}['{{{name}}}'] }{{/if}}</td>
33+
<th>Field</th>
34+
<th>Value</th>
4135
</tr>
42-
{{/each}}
43-
</tbody>
44-
</table>
45-
{error && (
46-
<div className='alert alert-danger' role='alert'>
47-
{error}
48-
</div>
49-
)}
50-
<Link href="/{{{name}}}"><a className="btn btn-primary">
51-
Back to list
52-
</a></Link>
53-
<Link href="/{{{name}}}/edit"><a className="btn btn-warning">
54-
Edit
55-
</a></Link>
56-
<button className='btn btn-danger' onClick={handleDelete}>
57-
<a>Delete</a>
58-
</button>
59-
</div>
60-
)};
36+
</thead>
37+
<tbody>
38+
{{#each fields}}
39+
<tr>
40+
<th scope="row">{{name}}</th>
41+
<td>{{#if reference}}<ReferenceLinks items={ {{{../lc}}}['{{{name}}}'] } type="{{{reference.title}}}" />{{else}}{ {{{../lc}}}['{{{name}}}'] }{{/if}}</td>
42+
</tr>
43+
{{/each}}
44+
</tbody>
45+
</table>
46+
{error && (
47+
<div className="alert alert-danger" role="alert">
48+
{error}
49+
</div>
50+
)}
51+
<Link href="/{{{name}}}">
52+
<a className="btn btn-primary">Back to list</a>
53+
</Link>
54+
<Link href="/{{{name}}}/edit">
55+
<a className="btn btn-warning">Edit</a>
56+
</Link>
57+
<button className="btn btn-danger" onClick={handleDelete}>
58+
<a>Delete</a>
59+
</button>
60+
</div>
61+
);
62+
};

templates/next/error/SubmissionError.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ export interface SubmissionErrorList {
55
export class SubmissionError extends Error {
66
public errors: SubmissionErrorList;
77

8-
constructor (errors: SubmissionErrorList) {
9-
super('Submit Validation Failed');
8+
constructor(errors: SubmissionErrorList) {
9+
super("Submit Validation Failed");
1010
this.errors = errors;
1111
Error.captureStackTrace(this, this.constructor);
1212
this.name = this.constructor.name;

templates/next/types/Collection.ts

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
export interface PagedCollection<T> {
2-
'@context'?: string;
3-
'@id'?: string;
4-
'@type'?: string;
5-
'{{{hydraPrefix}}}firstPage'?: string;
6-
'{{{hydraPrefix}}}itemsPerPage'?: number;
7-
'{{{hydraPrefix}}}lastPage'?: string;
8-
'{{{hydraPrefix}}}member'?: T[];
9-
'{{{hydraPrefix}}}nextPage'?: string;
10-
'{{{hydraPrefix}}}search'?: object;
11-
'{{{hydraPrefix}}}totalItems'?: number;
2+
"@context"?: string;
3+
"@id"?: string;
4+
"@type"?: string;
5+
"{{{hydraPrefix}}}firstPage"?: string;
6+
"{{{hydraPrefix}}}itemsPerPage"?: number;
7+
"{{{hydraPrefix}}}lastPage"?: string;
8+
"{{{hydraPrefix}}}member"?: T[];
9+
"{{{hydraPrefix}}}nextPage"?: string;
10+
"{{{hydraPrefix}}}search"?: object;
11+
"{{{hydraPrefix}}}totalItems"?: number;
1212
}

0 commit comments

Comments
 (0)