Skip to content

fix: fine tuning ad fixes #319

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 1, 2022
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
"eslint-check": "eslint-config-prettier src/index.js",
"build": "babel src -d lib --ignore '*.test.js'",
"watch": "babel --watch src -d lib --ignore '*.test.js'",
"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",
"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/next -g next && ./lib/index.js https://demo.api-platform.com ./tmp/vue -g vue",
"test-gen-custom": "rm -rf ./tmp && yarn build && babel src/generators/ReactGenerator.js src/generators/BaseGenerator.js -d ./tmp/gens && cp -r ./templates/react ./templates/react-common ./templates/entrypoint.js ./tmp/gens && ./lib/index.js https://demo.api-platform.com ./tmp/react-custom -g \"$(pwd)/tmp/gens/ReactGenerator.js\" -t ./tmp/gens",
"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",
"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"
Expand Down
6 changes: 3 additions & 3 deletions src/generators/BaseGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ export default class {
}
}

createFileFromPattern(pattern, dir, lc, context) {
createFileFromPattern(pattern, dir, value, context, templateValue = "foo") {
this.createFile(
sprintf(pattern, "foo"),
sprintf(`${dir}/${pattern}`, lc),
sprintf(pattern, templateValue),
sprintf(`${dir}/${pattern}`, value),
context
);
}
Expand Down
29 changes: 19 additions & 10 deletions src/generators/NextGenerator.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import chalk from "chalk";
import handlebars from "handlebars";
import hbh_comparison from "handlebars-helpers/lib/comparison";
import BaseGenerator from "./BaseGenerator";

export default class NextGenerator extends BaseGenerator {
Expand All @@ -15,8 +17,9 @@ export default class NextGenerator extends BaseGenerator {
"components/foo/Form.tsx",

// types
"types/Collection.ts",
"types/collection.ts",
"types/foo.ts",
"types/item.ts",

// pages
"pages/foos/[id]/index.tsx",
Expand All @@ -28,6 +31,8 @@ export default class NextGenerator extends BaseGenerator {
"utils/dataAccess.ts",
"utils/mercure.ts",
]);

handlebars.registerHelper("compare", hbh_comparison.compare);
}

help(resource) {
Expand Down Expand Up @@ -66,22 +71,25 @@ export default class NextGenerator extends BaseGenerator {

// Copy with patterned name
this.createDir(`${dir}/components/${context.lc}`);
this.createDir(`${dir}/pages/${context.lc}s`);
this.createDir(`${dir}/pages/${context.lc}s/[id]`);
this.createDir(`${dir}/pages/${context.name}`);
this.createDir(`${dir}/pages/${context.name}/[id]`);
[
// components
"components/%s/List.tsx",
"components/%s/Show.tsx",
"components/%s/Form.tsx",

// pages
"pages/%ss/[id]/index.tsx",
"pages/%ss/[id]/edit.tsx",
"pages/%ss/index.tsx",
"pages/%ss/create.tsx",
].forEach((pattern) =>
this.createFileFromPattern(pattern, dir, context.lc, context)
);
[
// pages
"pages/%s/[id]/index.tsx",
"pages/%s/[id]/edit.tsx",
"pages/%s/index.tsx",
"pages/%s/create.tsx",
].forEach((pattern) =>
this.createFileFromPattern(pattern, dir, context.name, context, "foos")
);

// interface pattern should be camel cased
this.createFile("types/foo.ts", `${dir}/types/${context.ucf}.ts`, context);
Expand All @@ -93,7 +101,8 @@ export default class NextGenerator extends BaseGenerator {
"components/common/ReferenceLinks.tsx",

// types
"types/Collection.ts",
"types/collection.ts",
"types/item.ts",

// utils
"utils/dataAccess.ts",
Expand Down
5 changes: 3 additions & 2 deletions src/generators/NextGenerator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ describe("generate", () => {
description: "An URL",
}),
];
const resource = new Resource("abc", "http://example.com/foos", {
const resource = new Resource("abcs", "http://example.com/foos", {
id: "abc",
title: "abc",
readableFields: fields,
Expand All @@ -46,7 +46,8 @@ describe("generate", () => {
"/components/common/ReferenceLinks.tsx",
"/components/common/Pagination.tsx",
"/types/Abc.ts",
"/types/Collection.ts",
"/types/collection.ts",
"/types/item.ts",
"/pages/abcs/[id]/index.tsx",
"/pages/abcs/[id]/edit.tsx",
"/pages/abcs/index.tsx",
Expand Down
2 changes: 1 addition & 1 deletion templates/next/components/common/Pagination.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Link from "next/link";
import { PagedCollection } from "../../types/Collection";
import { PagedCollection } from "../../types/collection";

interface Props {
collection: PagedCollection<unknown>;
Expand Down
9 changes: 7 additions & 2 deletions templates/next/components/foo/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,18 @@ export const Form: FunctionComponent<Props> = ({ {{{lc}}} }) => {
<input
name="{{name}}"
id="{{lc}}_{{name}}"
value={ values.{{name}} ?? "" }
{{#compare type "==" "dateTime" }}
value={values.{{name}}?.toLocaleString() ?? ""}
{{/compare}}
{{#compare type "!=" "dateTime" }}
value={values.{{name}} ?? ""}
{{/compare}}
type="{{type}}"
{{#if step}}step="{{{step}}}"{{/if}}
placeholder="{{{description}}}"
{{#if required}}required={true}{{/if}}
className={`form-control${errors.{{name}} && touched.{{name}} ? ' is-invalid' : ''}`}
aria-invalid={errors.{{name}} && touched.{{name~}} }
aria-invalid={errors.{{name}} && touched.{{name~}} ? 'true' : null}
onChange={handleChange}
onBlur={handleBlur}
/>
Expand Down
19 changes: 8 additions & 11 deletions templates/next/components/foo/Show.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { FunctionComponent, useState } from 'react';
import Link from 'next/link';
import { FunctionComponent, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/router";
import Head from "next/head";
import { fetch } from "../../utils/dataAccess";
import ReferenceLinks from '../common/ReferenceLinks';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ReferenceLinks not used on Show.tsx I just cleaned the code

import { {{{ucf}}} } from '../../types/{{{ucf}}}';
import Head from 'next/head'
import ReferenceLinks from "../common/ReferenceLinks";
import { {{{ucf}}} } from "../../types/{{{ucf}}}";

interface Props {
{{{lc}}}: {{{ucf}}};
text: string;
}

export const Show: FunctionComponent<Props> = ({ {{{lc}}} }) => {
export const Show: FunctionComponent<Props> = ({ {{{lc}}}, text }) => {
const [error, setError] = useState(null);
const router = useRouter();

Expand All @@ -30,11 +31,7 @@ export const Show: FunctionComponent<Props> = ({ {{{lc}}} }) => {
<div>
<Head>
<title>{`Show {{{ucf}}} ${ {{~lc}}['@id']}`}</title>
<script
type="application/ld+json"
>
{text}
</script>
<script type="application/ld+json" dangerouslySetInnerHTML={ { __html: text } } />
</Head>
<h1>{`Show {{{ucf}}} ${ {{~lc}}['@id']}`}</h1>
<table className="table table-responsive table-striped table-hover">
Expand Down
40 changes: 8 additions & 32 deletions templates/next/pages/foos/[id]/edit.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { GetStaticPaths, GetStaticProps, NextComponentType, NextPageContext } from "next";
import { Form } from "../../../components/{{{lc}}}/Form";
import { {{{ucf}}} } from "../../../types/{{{ucf}}}";
import { fetch } from "../../../utils/dataAccess";
import Head from "next/head";
import DefaultErrorPage from "next/error";
import { Form } from "../../../components/{{{lc}}}/Form";
import { {{{ucf}}} } from "../../../types/{{{ucf}}}";
import { fetch, getPaths } from "../../../utils/dataAccess";

interface Props {
{{{lc}}}: {{{ucf}}};
Expand All @@ -27,43 +27,19 @@ const Page: NextComponentType<NextPageContext, Props, Props> = ({ {{{lc}}} }) =>
};

export const getStaticProps: GetStaticProps = async ({ params }) => {
const response = await fetch(`/{{{name}}}/${params.id}`);

return {
props: {
{{{lc}}}: await fetch(`/{{{name}}}/${params.id}`),
{{{lc}}}: response.data,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't it better to pass the full response (including headers etc)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated after the use of react query

},
revalidate: 1,
};
}

export const getStaticPaths: GetStaticPaths = async () => {
try {
const response = await fetch("/{{{name}}}");
} catch (e) {
console.error(e);

return {
paths: [],
fallback: true,
};
}

const view = response.data['{{{hydraPrefix}}}view'];
const paths = response.data["{{{hydraPrefix}}}member"].map(({{{lc}}}) => `${ {{~lc}}['@id'] }/edit`);

if (view) {
try {
const {
'{{{hydraPrefix}}}last': last
} = view;
for (let page = 2; page <= parseInt(last.replace(/^\/{{{name}}}\?page=(\d+)/, '$1')); page++) {
paths.concat(
await fetch(`/{{{name}}}?page=${page}`).data["{{{hydraPrefix}}}member"].map(({{{lc}}}) => `${ {{~lc}}['@id'] }/edit`)
);
}
} catch (e) {
console.error(e);
}
}
const response = await fetch("/{{{name}}}");
const paths = await getPaths(response, "{{{name}}}", true);

return {
paths,
Expand Down
45 changes: 10 additions & 35 deletions templates/next/pages/foos/[id]/index.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import { GetStaticPaths, GetStaticProps, NextComponentType, NextPageContext } from "next";
import { Show } from "../../../components/{{{lc}}}/Show";
import { {{{ucf}}} } from "../../../types/{{{ucf}}}";
import { fetch } from "../../../utils/dataAccess";
import Head from "next/head";
import DefaultErrorPage from "next/error";
import { Show } from "../../../components/{{{lc}}}/Show";
import { {{{ucf}}} } from "../../../types/{{{ucf}}}";
import { fetch, getPaths } from "../../../utils/dataAccess";
import { useMercure } from "../../../utils/mercure";

interface Props {
{{{lc}}}: {{{ucf}}};
hubURL: null | string;
text: string;
};

const Page: NextComponentType<NextPageContext, Props, Props> = (props) => {
const {{{lc}}} = props.hubURL === null ? props.{{{lc}}} : useMercure(props.{{{lc}}}, props.hubURL);
const Page: NextComponentType<NextPageContext, Props, Props> = ({ {{{lc}}}, hubURL, text }) => {
const {{{lc}}}Data = useMercure({{{lc}}}, hubURL);

if (!{{{lc}}}) {
if (!{{{lc}}}Data) {
return <DefaultErrorPage statusCode={404} />;
}

Expand All @@ -25,7 +26,7 @@ const Page: NextComponentType<NextPageContext, Props, Props> = (props) => {
<title>{`Show {{{ucf}}} ${ {{~lc}}['@id'] }`}</title>
</Head>
</div>
<Show {{{lc}}}={ {{{lc}}} } text={ props.text } />
<Show {{{lc}}}={ {{{lc}}}Data } text={text} />
</div>
);
};
Expand All @@ -44,34 +45,8 @@ export const getStaticProps: GetStaticProps = async ({ params }) => {
}

export const getStaticPaths: GetStaticPaths = async () => {
try {
const response = await fetch("/{{{name}}}");
} catch (e) {
console.error(e);

return {
paths: [],
fallback: true,
};
}

const view = response.data['{{{hydraPrefix}}}view'];
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

response declared in try block but used outside

const paths = response.data["{{{hydraPrefix}}}member"].map(({{{lc}}}) => `${ {{~lc}}['@id'] }`);

if (view) {
try {
const {
'{{{hydraPrefix}}}last': last
} = view;
for (let page = 2; page <= parseInt(last.replace(/^\/{{{name}}}\?page=(\d+)/, '$1')); page++) {
paths.concat(
await fetch(`/{{{name}}}?page=${page}`).data["{{{hydraPrefix}}}member"].map(({{{lc}}}) => `${ {{~lc}}['@id'] }`)
);
}
} catch (e) {
console.error(e);
}
}
const response = await fetch("/{{{name}}}");
const paths = await getPaths(response, "{{{name}}}", false);

return {
paths,
Expand Down
2 changes: 1 addition & 1 deletion templates/next/pages/foos/create.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NextComponentType, NextPageContext } from "next";
import { Form } from "../../components/{{{lc}}}/Form";
import Head from "next/head";
import { Form } from "../../components/{{{lc}}}/Form";

const Page: NextComponentType<NextPageContext> = () => (
<div>
Expand Down
6 changes: 3 additions & 3 deletions templates/next/pages/foos/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { GetServerSideProps, NextComponentType, NextPageContext } from "next";
import Head from "next/head";
import { List } from "../../components/{{{lc}}}/List";
import { PagedCollection } from "../../types/Collection";
import { PagedCollection } from "../../types/collection";
import { {{{ucf}}} } from "../../types/{{{ucf}}}";
import { fetch } from "../../utils/dataAccess";
import Head from "next/head";
import Pagination from "../../components/common/Pagination";
import { useMercure } from "../../utils/mercure";

interface Props {
collection: PagedCollection<{{{ucf}}}>;
hubURL: string;
hubURL: string | null;
}

const Page: NextComponentType<NextPageContext, Props, Props> = (props) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import has from "lodash/has"

export interface PagedCollection<T> {
"@context"?: string;
"@id"?: string;
Expand All @@ -10,3 +12,6 @@ export interface PagedCollection<T> {
"{{{hydraPrefix}}}search"?: object;
"{{{hydraPrefix}}}totalItems"?: number;
}

export const isPagedCollection = <T>(data: any): data is PagedCollection<T> =>
has(data, "{{{hydraPrefix}}}member") && Array.isArray(data["{{{hydraPrefix}}}member"])
3 changes: 3 additions & 0 deletions templates/next/types/item.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import has from "lodash/has"

export const isItem = <T>(data: any): data is T => has(data, "@id")
Loading