Skip to content

feat: handle route prefix for Next and Nuxt #314

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

Closed
wants to merge 5 commits into from
Closed
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"handlebars": "^4.0.12",
"handlebars-helpers": "^0.10.0",
"isomorphic-fetch": "^3.0.0",
"lodash": "^4.17.21",
"mkdirp": "^1.0.4",
"prettier": "^2.2.1",
"sprintf-js": "^1.1.1"
Expand Down
45 changes: 32 additions & 13 deletions src/generators/NextGenerator.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import chalk from "chalk";
import camelCase from "lodash/camelCase";
import handlebars from "handlebars";
import hbh_string from "handlebars-helpers/lib/string";
import BaseGenerator from "./BaseGenerator";

export default class NextGenerator extends BaseGenerator {
Expand All @@ -19,15 +22,17 @@ export default class NextGenerator extends BaseGenerator {
"types/foo.ts",

// pages
"pages/foos/[id]/index.tsx",
"pages/foos/[id]/edit.tsx",
"pages/foos/index.tsx",
"pages/foos/create.tsx",
"pages/foo/[id]/index.tsx",
"pages/foo/[id]/edit.tsx",
"pages/foo/index.tsx",
"pages/foo/create.tsx",

// utils
"utils/dataAccess.ts",
"utils/mercure.ts",
]);

handlebars.registerHelper("replace", hbh_string.replace);
}

help(resource) {
Expand All @@ -40,13 +45,23 @@ export default class NextGenerator extends BaseGenerator {
generate(api, resource, dir) {
const lc = resource.title.toLowerCase();
const ucf = this.ucFirst(resource.title);
const path = resource.name.toLowerCase();
const camelName = camelCase(resource.name);
const { fields, imports } = this.parseFields(resource);

const context = {
name: resource.name,
lc,
uc: resource.title.toUpperCase(),
ucf,
camelName,
camelNameUcf: this.ucFirst(camelName),
path,
flatpath: path.replace("/", ""),
pathNesting: `${path
.split("/")
.map(() => "..")
.join("/")}/`,
fields,
formFields: this.buildFields(fields),
imports,
Expand All @@ -65,26 +80,30 @@ export default class NextGenerator extends BaseGenerator {
].forEach((dir) => this.createDir(dir, false));

// 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}/components/${context.path}`);
this.createDir(`${dir}/pages/${context.path}`);
this.createDir(`${dir}/pages/${context.path}/[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",
"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.lc, context)
this.createFileFromPattern(pattern, dir, context.path, context)
);

// interface pattern should be camel cased
this.createFile("types/foo.ts", `${dir}/types/${context.ucf}.ts`, context);
this.createFile(
"types/foo.ts",
`${dir}/types/${context.camelNameUcf}.ts`,
context
);

// copy with regular name
[
Expand Down
26 changes: 13 additions & 13 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("prefix/aBe_cd", "http://example.com/foos", {
id: "abc",
title: "abc",
readableFields: fields,
Expand All @@ -40,26 +40,26 @@ describe("generate", () => {

[
"/config/entrypoint.ts",
"/components/abc/List.tsx",
"/components/abc/Show.tsx",
"/components/abc/Form.tsx",
"/components/prefix/abe_cd/List.tsx",
"/components/prefix/abe_cd/Show.tsx",
"/components/prefix/abe_cd/Form.tsx",
"/components/common/ReferenceLinks.tsx",
"/components/common/Pagination.tsx",
"/types/Abc.ts",
"/types/PrefixABeCd.ts",
"/types/Collection.ts",
"/pages/abcs/[id]/index.tsx",
"/pages/abcs/[id]/edit.tsx",
"/pages/abcs/index.tsx",
"/pages/abcs/create.tsx",
"/pages/prefix/abe_cd/[id]/index.tsx",
"/pages/prefix/abe_cd/[id]/edit.tsx",
"/pages/prefix/abe_cd/index.tsx",
"/pages/prefix/abe_cd/create.tsx",
"/utils/dataAccess.ts",
"/utils/mercure.ts",
].forEach((file) => expect(fs.existsSync(tmpobj.name + file)).toBe(true));

[
"/components/abc/List.tsx",
"/components/abc/Show.tsx",
"/components/abc/Form.tsx",
"/types/Abc.ts",
"/components/prefix/abe_cd/List.tsx",
"/components/prefix/abe_cd/Show.tsx",
"/components/prefix/abe_cd/Form.tsx",
"/types/PrefixABeCd.ts",
].forEach((file) => {
expect(fs.existsSync(tmpobj.name + file)).toBe(true);
expect(fs.readFileSync(tmpobj.name + file, "utf8")).toMatch(/bar/);
Expand Down
24 changes: 15 additions & 9 deletions src/generators/NuxtGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ export default class NuxtGenerator extends BaseVueGenerator {
"mixins/update.js",

// pages
"pages/foos/new.vue",
"pages/foos/index.vue",
"pages/foos/_id.vue",
"pages/foo/new.vue",
"pages/foo/index.vue",
"pages/foo/_id.vue",

// store
"store/crud.js",
Expand All @@ -45,7 +45,6 @@ export default class NuxtGenerator extends BaseVueGenerator {

generateFiles(api, resource, dir, params) {
const context = super.getContextForResource(resource, params);
const lc = context.lc;

[
`${dir}/config`,
Expand Down Expand Up @@ -106,7 +105,10 @@ export default class NuxtGenerator extends BaseVueGenerator {

this.createEntrypoint(api.entrypoint, `${dir}/config/entrypoint.js`);

for (let dir of [`${dir}/components/${lc}`, `${dir}/pages/${lc}s`]) {
for (let dir of [
`${dir}/components/${context.path}`,
`${dir}/pages/${context.path}`,
]) {
this.createDir(dir);
}

Expand All @@ -118,17 +120,21 @@ export default class NuxtGenerator extends BaseVueGenerator {
"components/%s/Form.vue",

// pages
"pages/%ss/new.vue",
"pages/%ss/index.vue",
"pages/%ss/_id.vue",
"pages/%s/new.vue",
"pages/%s/index.vue",
"pages/%s/_id.vue",
].forEach((pattern) =>
this.createFileFromPattern(pattern, dir, context.path, context)
);

[
// service
"services/%s.js",

// store
"store/%s.js",
].forEach((pattern) =>
this.createFileFromPattern(pattern, dir, lc, context)
this.createFileFromPattern(pattern, dir, context.flatpath, context)
);

// components
Expand Down
14 changes: 7 additions & 7 deletions src/generators/NuxtGenerator.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("prefix/aBe_cd", "http://example.com/foos", {
id: "foo",
title: "Foo",
readableFields: fields,
Expand All @@ -42,23 +42,23 @@ describe("generate", () => {

generator.generate(api, resource, tmpobj.name).then(() => {
[
"/components/foo/Form.vue",
"/components/prefix/abecd/Form.vue",
"/components/InputDate.vue",
"/components/Loading.vue",
"/components/Alert.vue",
"/components/Toolbar.vue",
"/config/entrypoint.js",
"/error/SubmissionError.js",
"/services/api.js",
"/services/foo.js",
"/store/foo.js",
"/services/prefixabecd.js",
"/store/prefixabecd.js",
"/store/notifications.js",
"/utils/dates.js",
"/utils/fetch.js",
"/utils/hydra.js",
"/pages/foos/_id.vue",
"/pages/foos/index.vue",
"/pages/foos/new.vue",
"/pages/prefix/abecd/_id.vue",
"/pages/prefix/abecd/index.vue",
"/pages/prefix/abecd/new.vue",
].forEach((file) => {
expect(fs.existsSync(tmpobj.name + file)).toBe(true);
});
Expand Down
11 changes: 11 additions & 0 deletions src/generators/VueBaseGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import handlebars from "handlebars";
import hbh_comparison from "handlebars-helpers/lib/comparison";
import hbh_array from "handlebars-helpers/lib/array";
import hbh_string from "handlebars-helpers/lib/string";
import camelCase from "lodash/camelCase";
import { sprintf } from "sprintf-js";

export default class extends BaseGenerator {
Expand Down Expand Up @@ -132,11 +133,21 @@ export default class extends BaseGenerator {

const labels = this.commonLabelTexts();

const path = resource.name.toLowerCase().replace("_", "");

return {
title: resource.title,
name: resource.name,
lc,
uc: resource.title.toUpperCase(),
camelName: camelCase(resource.name),
path,
flatpath: path.replace("/", ""),
snakePath: path.replace("/", "-"),
pathNesting: `${path
.split("/")
.map(() => "..")
.join("/")}/`,
fields,
dateTypes,
listContainsDate,
Expand Down
14 changes: 7 additions & 7 deletions templates/next/components/foo/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,22 @@ import { FunctionComponent, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/router";
import { ErrorMessage, Formik } from "formik";
import { fetch } from "../../utils/dataAccess";
import { {{{ucf}}} } from '../../types/{{{ucf}}}';
import { fetch } from "../{{{pathNesting}}}utils/dataAccess";
import { {{{camelNameUcf}}} } from '../{{{pathNesting}}}types/{{{camelNameUcf}}}';

interface Props {
{{{lc}}}?: {{{ucf}}};
{{{camelName}}}?: {{{camelNameUcf}}};
}

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

const handleDelete = async () => {
if (!window.confirm("Are you sure you want to delete this item?")) return;

try {
await fetch({{{lc}}}['@id'], { method: "DELETE" });
await fetch({{{camelName}}}['@id'], { method: "DELETE" });
router.push("/{{{name}}}");
} catch (error) {
setError(`Error when deleting the resource: ${error}`);
Expand All @@ -27,9 +27,9 @@ export const Form: FunctionComponent<Props> = ({ {{{lc}}} }) => {

return (
<div>
<h1>{ {{{lc}}} ? `Edit {{{ucf}}} ${ {{~lc}}['@id']}` : `Create {{{ucf}}}` }</h1>
<h1>{ {{{camelName}}} ? `Edit {{{ucf}}} ${ {{~camelName}}['@id']}` : `Create {{{ucf}}}` }</h1>
<Formik
initialValues={ {{~lc}} ? {...{{lc~}} } : new {{{ucf}}}()}
initialValues={ {{~camelName}} ? {...{{camelName~}} } : new {{{camelNameUcf}}}()}
validate={(values) => {
const errors = {};
// add your validation logic here
Expand Down
20 changes: 10 additions & 10 deletions templates/next/components/foo/List.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { FunctionComponent } from "react";
import Link from "next/link";
import ReferenceLinks from "../../components/common/ReferenceLinks";
import { {{{ucf}}} } from '../../types/{{{ucf}}}';
import ReferenceLinks from "../{{{pathNesting}}}components/common/ReferenceLinks";
import { {{{camelNameUcf}}} } from '../{{{pathNesting}}}types/{{{camelNameUcf}}}';

interface Props {
{{{name}}}: {{{ucf}}}[];
{{{camelName}}}: {{{camelNameUcf}}}[];
}

export const List: FunctionComponent<Props> = ({ {{{name}}} }) => (
export const List: FunctionComponent<Props> = ({ {{{camelName}}} }) => (
<div>
<h1>{{{ucf}}} List</h1>
<Link href="/{{{name}}}/create">
Expand All @@ -24,15 +24,15 @@ export const List: FunctionComponent<Props> = ({ {{{name}}} }) => (
</tr>
</thead>
<tbody>
{ {{{name}}} && ({{{name}}}.length !== 0) && {{{name}}}.map( ( {{{lc}}} ) => (
<tr key={ {{{lc}}}['@id'] }>
<th scope="row"><ReferenceLinks items={ {{{lc}}}['@id'] } type="{{{lc}}}" /></th>
{ {{{camelName}}} && ({{{camelName}}}.length !== 0) && {{{camelName}}}.map( ( {{{camelName}}}Item ) => (
<tr key={ {{{camelName}}}Item['@id'] }>
<th scope="row"><ReferenceLinks items={ {{{camelName}}}Item['@id'] } type="{{{lc}}}" /></th>
{{#each fields}}
<td>{{#if reference}}<ReferenceLinks items={ {{{../lc}}}['{{{name}}}'] } type="{{{reference.title}}}" />{{else}}{ {{{../lc}}}['{{{name}}}'] }{{/if}}</td>
<td>{{#if reference}}<ReferenceLinks items={ {{{../camelName}}}Item['{{{name}}}'] } type="{{{reference.title}}}" />{{else}}{ {{{../camelName}}}Item['{{{name}}}'] }{{/if}}</td>
{{/each}}
<td><ReferenceLinks items={ {{{lc}}}['@id'] } type="{{{lc}}}" useIcon={true} /></td>
<td><ReferenceLinks items={ {{{camelName}}}Item['@id'] } type="{{{lc}}}" useIcon={true} /></td>
<td>
<Link href={`${ {{~lc}}["@id"]}/edit`}>
<Link href={`${ {{~camelName}}Item["@id"]}/edit`}>
<a>
<i className="bi bi-pen" aria-hidden="true" />
<span className="sr-only">Edit</span>
Expand Down
Loading