Skip to content
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

optinal rest parameterの追加とテスト拡充 #2

Merged
merged 19 commits into from
Apr 17, 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
7 changes: 3 additions & 4 deletions .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ jobs:
steps:
- name: Setup repo
uses: actions/checkout@v3
- run: cd packages

- name: Setup Deno
uses: denoland/setup-deno@v1
# uses: denoland/setup-deno@004814556e37c54a2f6e31384c9e18e983317366
Expand All @@ -39,5 +37,6 @@ jobs:
- name: Run linter
run: deno lint

- name: Run tests
run: deno test -A --unstable --allow-write --allow-read
- name: Run tests at packages
# Need to work with packages directory to resolve snapshot test paths
run: cd packages && deno test -A --unstable --allow-write --allow-read
12 changes: 5 additions & 7 deletions packages/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ Couscous is a utility tool for next.js that automatically generates route functi

`deno run --allow-read --allow-write https://deno.land/x/couscous/index.ts utils/route/generated.ts`

#### options
### options

- `-t <path>` tsconfig path. default `tsconfig.json`
- `-r <path>` page root. default `pages`

`deno run --allow-read --allow-write https://deno.land/x/couscous/index.ts src/utils/route/generated.ts -t configs/dev.tsconfig.json -r src/pages`

## Example

### directory structure
Expand All @@ -25,15 +27,11 @@ Couscous is a utility tool for next.js that automatically generates route functi
```typescript:generated.ts
interface RouteOption {
query?: { [key: string]: string };
hash?: `#${string}`;
fragment?: string;
}

type Identity = "/" | "/users/[id]/" | "/api/hello/" | "/items/[items]/";

function toSearch(searchParams: URLSearchParams): string {
return searchParams.toString() ? "?" + searchParams.toString() : "";
}

export function route(identity: "/", option?: RouteOption): string;
export function route(
identity: "/users/[id]/",
Expand Down Expand Up @@ -74,7 +72,7 @@ export function route(
}
const option = args[index] as RouteOption | undefined;
const searchParams = new URLSearchParams(option?.query ?? {});
return `${path}${toSearch(searchParams)}${option?.hash}`;
return `${path}${searchParams.toString() && "?" + searchParams.toString()}${option?.fragment && "#" + option?.fragment}`;
}

```
Expand Down
5 changes: 3 additions & 2 deletions packages/_snapshots/generator_test_case0.snapshot
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
function route(identity: "/fuga", option?: RouteOption): string;
function route(identity: "/hoge/[hoge]", hoge: string, option?: RouteOption): string;
function route(identity: "/piyo/[...slug]", slug: string[], option?: RouteOption): string;
function route(identity: "/foo/[foo]/[...bar]", foo: string, bar: string[], option?: RouteOption): string;
function route(identity: "/piyo/[...slug]", slug: [string, ...string[]], option?: RouteOption): string;
function route(identity: "/foo/[foo]/[...bar]", foo: string, bar: [string, ...string[]], option?: RouteOption): string;
function route(identity: "/foo/[foo]/[[...piyo]]", foo: string, bar: string[], option?: RouteOption): string;
function route() {
return ""
}
1 change: 1 addition & 0 deletions packages/_snapshots/structure_test_identitytype.snapshot
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
type Identity = "foo" | "bar" | "hoge" | "piyo" | "fuga/${id}";
1 change: 1 addition & 0 deletions packages/_snapshots/structure_test_parametertype.snapshot
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
type ParameterType = string | [string, ...string[]] | string[] | RouteOption | undefined;
4 changes: 4 additions & 0 deletions packages/_snapshots/structure_test_routeoption.snapshot
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
interface RouteOption {
query?: { [key: string]: string };
fragment?: string;
}
17 changes: 7 additions & 10 deletions packages/_test_helper/equal.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
import {
assertEquals,
equal,
} from "https://deno.land/std@0.132.0/testing/asserts.ts";
import { copy } from "https://deno.land/std@0.132.0/fs/mod.ts";
import { assertEquals } from "https://deno.land/std@0.132.0/testing/asserts.ts";
import { copy, ensureFile } from "https://deno.land/std@0.132.0/fs/mod.ts";
export const assertSnapshot = async (
receivedPath: string,
expectedPath: string
) => {
const [received, expected] = await Promise.all([
Deno.readTextFile(receivedPath),
Deno.readTextFile(expectedPath),
]);
if (Deno.args.includes("update_snapshot")) {
if (equal(received, expected)) return;
await ensureFile(expectedPath);
await copy(receivedPath, expectedPath, { overwrite: true });
} else {
const [received, expected] = await Promise.all([
Deno.readTextFile(receivedPath),
Deno.readTextFile(expectedPath),
]);
assertEquals(received, expected);
}
};
43 changes: 36 additions & 7 deletions packages/converter_test.ts → packages/converter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,35 @@ Deno.test("convertToBase", () => {
};
const testCases: TestCase<typeof convertToBase>[] = [
["pages", { ...baseEntry, name: "index.ts", path: "pages/index.ts" }, "/"],
[
"pages",
{ ...baseEntry, name: "user.ts", path: "pages/user.ts" },
"/user",
],
[
"pages",
{ ...baseEntry, name: "[id].ts", path: "pages/user/[id].ts" },
"/user/[id]",
],
[
"pages",
{ ...baseEntry, name: "index.ts", path: "pages/items/index.ts" },
"/items",
],
[
"pages",
{ ...baseEntry, name: "index.ts", path: "pages/items/[id]/index.ts" },
"/items/[id]",
],
[
"pages",
{
...baseEntry,
name: "index.ts",
path: "pages/items/[[...id]]/index.ts",
},
"/items/[[...id]]",
],
];
testCases.forEach((testcase) => {
assertEquals(convertToBase(testcase[0], testcase[1]), testcase[2]);
Expand All @@ -26,7 +55,7 @@ Deno.test("convertToDynamicParam", () => {
const testCases: TestCase<typeof convertToDynamicParam>[] = [
["", undefined],
["hoge", undefined],
["[id]", { type: "param", name: "id" }],
["[id]", { type: "single", name: "id" }],
["[...slug]", { type: "rest", name: "slug", isOptional: false }],
["[[...foo]]", { type: "rest", name: "foo", isOptional: true }],
];
Expand Down Expand Up @@ -71,8 +100,8 @@ Deno.test("convertToRoute", () => {
isSymlink: false,
},
{
identity: "/fuga/",
template: "/fuga/",
identity: "/fuga",
template: "/fuga",
params: [],
},
],
Expand All @@ -86,8 +115,8 @@ Deno.test("convertToRoute", () => {
isSymlink: false,
},
{
identity: "/fuga/",
template: "/fuga/",
identity: "/fuga",
template: "/fuga",
params: [],
},
],
Expand All @@ -101,8 +130,8 @@ Deno.test("convertToRoute", () => {
isSymlink: false,
},
{
identity: "/fuga/[...slug]/",
template: '/fuga/${slug.join("/")}/',
identity: "/fuga/[...slug]",
template: '/fuga/${slug.join("/")}',
params: [
{
type: "rest",
Expand Down
12 changes: 7 additions & 5 deletions packages/converter.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import type { WalkEntry } from "https://deno.land/std@0.130.0/fs/mod.ts";
import { parse as parsePath } from "https://deno.land/std@0.130.0/path/mod.ts";
import type { Route, DynamicParam } from "./type.ts";
import type { Route, DynamicParam } from "./type/index.ts";
import { parseToDynamicParams } from "./parser.ts";

export const convertToBase = (root: string, entry: WalkEntry): string => {
const parsed = parsePath(entry.path);
const base = [
parsed.dir.replace(new RegExp(`^${root}`), ""),
parsed.name !== "index" ? `${parsed.name}/` : "",
].join("/");
return base;
parsed.name !== "index" ? `${parsed.name}` : "",
]
.filter((val, index) => !index || val.length)
.join("/");
return base ? base : "/";
};

export const convertToDynamicParam = (
Expand All @@ -34,7 +36,7 @@ export const convertToDynamicParam = (
const key = name.match(/^\[(\w+)\]$/);
if (key) {
return {
type: "param",
type: "single",
name: key[1],
};
} else {
Expand Down
17 changes: 14 additions & 3 deletions packages/generator_test.ts → packages/generator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { test } from "./_test_helper/fileSystem.ts";
import { assertSnapshot } from "./_test_helper/equal.ts";
import { addEntryOverloads } from "./generator.ts";

test("addEntryOverloads", async (source) => {
test("addEntryOverloads with snapshot", async (source) => {
const constructor = source.addFunction({
name: "route",
kind: StructureKind.Function,
Expand All @@ -12,11 +12,13 @@ test("addEntryOverloads", async (source) => {
addEntryOverloads(
[
{ identity: "/fuga", template: "/fuga/", params: [] },
// single parameter
{
identity: "/hoge/[hoge]",
template: "/hoge/${hoge}",
params: [{ name: "hoge", type: "param" }],
params: [{ name: "hoge", type: "single" }],
},
// rest parameter
{
identity: "/piyo/[...slug]",
template: '/piyo/${slug.join("/")}',
Expand All @@ -26,10 +28,19 @@ test("addEntryOverloads", async (source) => {
identity: "/foo/[foo]/[...bar]",
template: '/foo/${foo}/${bar.join("/")}',
params: [
{ name: "foo", type: "param" },
{ name: "foo", type: "single" },
{ name: "bar", type: "rest", isOptional: false },
],
},
// optional rest parameter
{
identity: "/foo/[foo]/[[...piyo]]",
template: '/foo/${foo}/${piyo.join("/")}',
params: [
{ name: "foo", type: "single" },
{ name: "bar", type: "rest", isOptional: true },
],
},
],
constructor
);
Expand Down
36 changes: 13 additions & 23 deletions packages/generator.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { FunctionDeclaration } from "https://deno.land/x/ts_morph@14.0.0/mod.ts";
import type { Route } from "./type.ts";

const toType = (type: "param" | "rest") =>
type === "param" ? "string" : "string[]";
import { Route, ParameterType } from "./type/index.ts";

export const addEntryOverloads = (
routes: Route[],
Expand All @@ -14,7 +11,7 @@ export const addEntryOverloads = (
{ name: "identity", type: `"${route.identity}"` },
...route.params.map((parameter) => ({
name: parameter.name,
type: toType(parameter.type),
type: ParameterType.toType(parameter),
})),
{
name: "option",
Expand All @@ -33,38 +30,31 @@ export const addRoutesHandler = (
) => {
routesHandler.addStatements((writer) => {
writer.writeLine("let path: string;");
writer.writeLine("let index: number;");
writer.writeLine("let optionIndex: number;");
writer.write("switch (identity)").block(() => {
routes.forEach((route) => {
writer.writeLine(`case "${route.identity}":`);
writer.block(() => {
route.params.forEach((key, index) => {
switch (key.type) {
case "param":
writer.writeLine(`const ${key.name} = args[${index}];`);
break;
case "rest":
writer.writeLine(
`const ${key.name} = args[${index}] as string[]`
);
break;
}
route.params.forEach((param, index) => {
writer.writeLine(
`const ${param.name} = args[${index}] as ${ParameterType.toType(
param
)};`
);
});
writer.writeLine("path = `" + route.template + "`;");
const optionIndex = route.params.length;
writer.writeLine(`index = ${optionIndex};`);
writer.writeLine(`optionIndex = ${optionIndex};`);
writer.write("break;");
});
});
});
writer.writeLine(
"const option = args[index] as (RouteOption | undefined);"
);
writer.writeLine(
"const searchParams = new URLSearchParams(option?.query ?? {});"
"const option = args[optionIndex] as (RouteOption | undefined);"
);
writer.writeLine("const query = new URLSearchParams(option?.query ?? {});");
writer.writeLine(
"return `${path}${toSearch(searchParams)}${option?.hash}`"
'return `${path}${query.toString() && "?" + query.toString}${option?.fragment && "#" + option.fragment}`'
);
});
};
Loading