Skip to content

Commit 5e37f48

Browse files
committed
fix: last fixes
1 parent d4f068e commit 5e37f48

File tree

9 files changed

+58
-35
lines changed

9 files changed

+58
-35
lines changed

src/generators/BaseGenerator.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,10 @@ export default class {
3737
}
3838
}
3939

40-
createFileFromPattern(pattern, dir, lc, context) {
40+
createFileFromPattern(pattern, dir, value, context, templateValue = "foo") {
4141
this.createFile(
42-
sprintf(pattern, "foo"),
43-
sprintf(`${dir}/${pattern}`, lc),
42+
sprintf(pattern, templateValue),
43+
sprintf(`${dir}/${pattern}`, value),
4444
context
4545
);
4646
}

src/generators/NextGenerator.js

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ export default class NextGenerator extends BaseGenerator {
1717
"components/foo/Form.tsx",
1818

1919
// types
20-
"types/Collection.ts",
20+
"types/collection.ts",
2121
"types/foo.ts",
22+
"types/item.ts",
2223

2324
// pages
2425
"pages/foos/[id]/index.tsx",
@@ -30,7 +31,7 @@ export default class NextGenerator extends BaseGenerator {
3031
"utils/dataAccess.ts",
3132
"utils/mercure.ts",
3233
]);
33-
34+
3435
handlebars.registerHelper("compare", hbh_comparison.compare);
3536
}
3637

@@ -70,22 +71,25 @@ export default class NextGenerator extends BaseGenerator {
7071

7172
// Copy with patterned name
7273
this.createDir(`${dir}/components/${context.lc}`);
73-
this.createDir(`${dir}/pages/${context.lc}s`);
74-
this.createDir(`${dir}/pages/${context.lc}s/[id]`);
74+
this.createDir(`${dir}/pages/${context.name}`);
75+
this.createDir(`${dir}/pages/${context.name}/[id]`);
7576
[
7677
// components
7778
"components/%s/List.tsx",
7879
"components/%s/Show.tsx",
7980
"components/%s/Form.tsx",
80-
81-
// pages
82-
"pages/%ss/[id]/index.tsx",
83-
"pages/%ss/[id]/edit.tsx",
84-
"pages/%ss/index.tsx",
85-
"pages/%ss/create.tsx",
8681
].forEach((pattern) =>
8782
this.createFileFromPattern(pattern, dir, context.lc, context)
8883
);
84+
[
85+
// pages
86+
"pages/%s/[id]/index.tsx",
87+
"pages/%s/[id]/edit.tsx",
88+
"pages/%s/index.tsx",
89+
"pages/%s/create.tsx",
90+
].forEach((pattern) =>
91+
this.createFileFromPattern(pattern, dir, context.name, context, "foos")
92+
);
8993

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

99103
// types
100-
"types/Collection.ts",
104+
"types/collection.ts",
105+
"types/item.ts",
101106

102107
// utils
103108
"utils/dataAccess.ts",

templates/next/components/common/Pagination.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import Link from "next/link";
2-
import { PagedCollection } from "../../types/Collection";
2+
import { PagedCollection } from "../../types/collection";
33

44
interface Props {
55
collection: PagedCollection<unknown>;

templates/next/pages/foos/create.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { NextComponentType, NextPageContext } from "next";
2-
import { Form } from "../../components/{{{lc}}}/Form";
32
import Head from "next/head";
3+
import { Form } from "../../components/{{{lc}}}/Form";
44

55
const Page: NextComponentType<NextPageContext> = () => (
66
<div>

templates/next/pages/foos/index.tsx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
import { GetServerSideProps, NextComponentType, NextPageContext } from "next";
2+
import Head from "next/head";
23
import { List } from "../../components/{{{lc}}}/List";
3-
import { PagedCollection } from "../../types/Collection";
4+
import { PagedCollection } from "../../types/collection";
45
import { {{{ucf}}} } from "../../types/{{{ucf}}}";
56
import { fetch } from "../../utils/dataAccess";
6-
import Head from "next/head";
77
import Pagination from "../../components/common/Pagination";
88
import { useMercure } from "../../utils/mercure";
99

1010
interface Props {
1111
collection: PagedCollection<{{{ucf}}}>;
12-
hubURL: string;
12+
hubURL: string | null;
1313
}
1414

1515
const Page: NextComponentType<NextPageContext, Props, Props> = (props) => {

templates/next/types/Collection.ts renamed to templates/next/types/collection.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import has from "lodash/has"
2+
13
export interface PagedCollection<T> {
24
"@context"?: string;
35
"@id"?: string;
@@ -10,3 +12,6 @@ export interface PagedCollection<T> {
1012
"{{{hydraPrefix}}}search"?: object;
1113
"{{{hydraPrefix}}}totalItems"?: number;
1214
}
15+
16+
export const isPagedCollection = <T>(data: any): data is PagedCollection<T> =>
17+
has(data, "{{{hydraPrefix}}}member") && Array.isArray(data["{{{hydraPrefix}}}member"])

templates/next/types/item.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import has from "lodash/has"
2+
3+
export const isItem = <T>(data: any): data is T => has(data, "@id")

templates/next/utils/dataAccess.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ export const fetch = async (id: string, init: RequestInit = {}) => {
4040
const json = JSON.parse(text);
4141
if (resp.ok) {
4242
return {
43-
hubURL: extractHubURL(resp)?.toString(), // URL cannot be serialized as JSON, must be sent as string
43+
hubURL: extractHubURL(resp)?.toString() || null, // URL cannot be serialized as JSON, must be sent as string
4444
data: normalize(json),
4545
text,
4646
};
@@ -58,7 +58,7 @@ export const fetch = async (id: string, init: RequestInit = {}) => {
5858
throw { defaultErrorMsg, status, fields };
5959
};
6060

61-
export const normalize = (data: unknown) => {
61+
export const normalize = (data: any) => {
6262
if (has(data, "{{{hydraPrefix}}}member")) {
6363
// Normalize items in collections
6464
data["{{{hydraPrefix}}}member"] = data[
@@ -69,7 +69,7 @@ export const normalize = (data: unknown) => {
6969
}
7070

7171
// Flatten nested documents
72-
return mapValues(data as Object, (value) =>
72+
return mapValues(data, (value) =>
7373
Array.isArray(value)
7474
? value.map((v) => get(v, "@id", v))
7575
: get(value, "@id", value)

templates/next/utils/mercure.ts

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import { useEffect, useState } from "react";
2-
import has from "lodash/has";
3-
import { PagedCollection } from "../types/Collection";
2+
import { PagedCollection, isPagedCollection } from "../types/collection";
3+
import { isItem } from "../types/item";
44
import { normalize } from "./dataAccess";
55

6-
const mercureSubscribe = (hubURL: string, data: unknown | PagedCollection<unknown>, setData: (data: unknown) => void) => {
6+
const mercureSubscribe = <T>(hubURL: string, data: T | PagedCollection<T>, setData: (data: T) => void) => {
77
const url = new URL(hubURL, window.origin);
88
url.searchParams.append("topic", (new URL(data["@id"], window.origin)).toString());
99
const eventSource = new EventSource(url.toString());
@@ -12,34 +12,44 @@ const mercureSubscribe = (hubURL: string, data: unknown | PagedCollection<unknow
1212
return eventSource;
1313
}
1414

15-
export const useMercure = (deps: unknown | PagedCollection<unknown>, hubURL: string | null) => {
15+
export const useMercure = <T>(deps: T | PagedCollection<T>, hubURL: string | null) => {
1616
const [data, setData] = useState(deps);
1717

1818
useEffect(() => {
1919
setData(deps);
2020
}, [deps]);
2121

2222
useEffect(() => {
23-
if (!has(data, "{{{hydraPrefix}}}member") && !has(data, "@id")) {
23+
if (!hubURL || !data) {
24+
return;
25+
}
26+
27+
if (!isPagedCollection(data) && !isItem(data)) {
2428
console.error("Object sent is not in JSON-LD format.");
2529

30+
return;
2631
}
2732

28-
if (hubURL && has(data, "{{{hydraPrefix}}}member") && Array.isArray(data["{{{hydraPrefix}}}member"]) && data["{{{hydraPrefix}}}member"].length !== 0) {
33+
if (isPagedCollection(data) && data["{{{hydraPrefix}}}member"].length !== 0) {
34+
const eventSources: EventSource[] = [];
2935
// It's a PagedCollection
30-
data["{{{hydraPrefix}}}member"].forEach((obj, pos) => mercureSubscribe(hubURL, obj, (datum) => {
31-
data["{{{hydraPrefix}}}member"][pos] = datum;
32-
setData(data);
33-
}));
34-
36+
data["{{{hydraPrefix}}}member"].forEach((obj, pos) => {
37+
eventSources.push(mercureSubscribe(hubURL, obj, (datum: T) => {
38+
data["{{{hydraPrefix}}}member"][pos] = datum;
39+
setData({ ...data });
40+
}));
41+
});
42+
43+
return () => {
44+
eventSources.forEach((eventSource) => eventSource.close());
45+
};
3546
}
3647

3748
// It's a single object
3849
const eventSource = mercureSubscribe(hubURL, data, setData);
3950

4051
return () => {
41-
eventSource.removeEventListener("message", (event) => setData(normalize(JSON.parse(event.data))));
42-
52+
eventSource.close();
4353
};
4454
}, [data]);
4555

0 commit comments

Comments
 (0)