Skip to content

Commit

Permalink
fix(formatByPrettier.ts): to async function
Browse files Browse the repository at this point in the history
fix #151
  • Loading branch information
araera111 committed Aug 30, 2024
1 parent d6a40c4 commit 567b9bb
Show file tree
Hide file tree
Showing 9 changed files with 60 additions and 78 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"mysql-to-zod": "tsx ./src/main.ts",
"dev": "tsx ./src/main.ts",
"build": "zx ./build.mjs && zx ./addShebang.mjs",
"debugBuild": "esbuild ./src/main.ts --bundle --sourcemap --platform=node --outfile=./dist/main.js",
"debugBuild": "esbuild ./src/main.ts --bundle --sourcemap --platform=node --outfile=./dist/main.js --external:prettier",
"test": "vitest",
"type": "tsc --noEmit",
"lint": "pnpm biome check --apply ./src",
Expand Down Expand Up @@ -68,4 +68,4 @@
"node": "18.17.0",
"npm": "9.8.1"
}
}
}
8 changes: 4 additions & 4 deletions src/features/sync/utils/syncUtil.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe("schemaInformationToText", () => {
});

describe("mergeSchemaTextWithOldInformation 完成したschemaTextと以前のschemaInformationを合体する関数", () => {
it("case1", () => {
it("case1", async () => {
const schemaName = "aaaSchema";
const schemaInformation: SchemaInformation = {
tableName: "aaaSchema",
Expand All @@ -32,7 +32,7 @@ describe("mergeSchemaTextWithOldInformation 完成したschemaTextと以前のsc
const result = `export const aaaSchema = z.object({
DB_ID: z.number().optional(),
});`;
const ex = mergeSchemaTextWithOldInformation({
const ex = await mergeSchemaTextWithOldInformation({
schemaInformation,
schemaName,
schemaText,
Expand Down Expand Up @@ -89,7 +89,7 @@ describe("getSchemaInformation", () => {
});

describe("formatByPrettier", () => {
it("case1", () => {
it("case1", async () => {
const str =
"export const myTodoListSchema = z.object({ id: z.number(), status: z.string(), task: z.string(), description: z.string().nullish(), due_date: z.date().nullish(), created_at: z.date().nullish(), updated_at: z.date().nullish(),});";
const result = `export const myTodoListSchema = z.object({
Expand All @@ -102,6 +102,6 @@ describe("formatByPrettier", () => {
updated_at: z.date().nullish(),
});
`;
expect(formatByPrettier(str)).toBe(result);
expect(await formatByPrettier(str)).toBe(result);
});
});
49 changes: 16 additions & 33 deletions src/process/buildSchemaText/buildSchemaText.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { A, O, R, pipe } from "@mobily/ts-belt";
import { R } from "@mobily/ts-belt";
import { produce } from "immer";
import type { SchemaInformation } from "../../features/sync/types/syncType";
import type { MysqlToZodOption } from "../../options/options";
Expand Down Expand Up @@ -29,46 +29,29 @@ export const buildSchemaText = async ({
draft.push("import { globalSchema } from './globalSchema';");
}).join("\n");

const loop = async (
restTables: readonly string[],
result: SchemaResult,
): Promise<R.Result<SchemaResult, string>> => {
if (A.isEmpty(restTables)) return R.Ok(result);
/* isEmptyで調べているのでgetExnを使用する */
const headTable = pipe(restTables, A.head, O.getExn);
const tailTables = pipe(restTables, A.tail, O.getExn);
const result: SchemaResult = {
schema: "",
columns: [],
};

const tableDefinition = await getTableDefinition(
headTable,
for (const table of tables) {
const definition = await getTableDefinition(
table,
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
option.dbConnection as any,
);
const schemaTextEither = createSchemaFile(
tableDefinition,
const schema = await createSchemaFile(
definition,
option,
schemaInformationList,
);
if (R.isOk(schema)) {
result.schema += R.getExn(schema).schema;
result.columns.push(...R.getExn(schema).columns);
}
}

return R.match(
schemaTextEither,
(ok) => {
const nextResult = produce(result, (draft) => {
draft.schema += ok.schema;
draft.columns.push(...ok.columns);
});
return loop(tailTables, nextResult);
},
async (err) => {
return await R.Error(err);
},
);
};
const schemaTexts = await loop(tables, {
schema: "",
columns: [],
});

return R.flatMap(schemaTexts, (x) => {
return R.flatMap(R.Ok(result), (x) => {
const text = strListToStrLf([importDeclaration, x.schema]);
return R.Ok({ text, columns: x.columns, option });
});
Expand Down
12 changes: 6 additions & 6 deletions src/process/buildSchemaText/utils/createSchema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Column } from "../types/buildSchemaTextType";
import { createSchema } from "./createSchema";

describe("createSchema", () => {
it("case 1 separate = false", () => {
it("case 1 separate = false", async () => {
const tableName = "todo";
const columns: Column[] = [
{
Expand Down Expand Up @@ -32,7 +32,7 @@ export type Todo = z.infer<typeof todoSchema>;`;
};

expect(
createSchema({
await createSchema({
tableName,
tableComment: undefined,
columns,
Expand All @@ -43,7 +43,7 @@ export type Todo = z.infer<typeof todoSchema>;`;
).toStrictEqual(result);
});

it("case2 separate = true", () => {
it("case2 separate = true", async () => {
const tableName = "todo";
const columns: Column[] = [
{
Expand Down Expand Up @@ -75,7 +75,7 @@ export type InsertTodo = z.infer<typeof insertTodoSchema>;`;
};

expect(
createSchema({
await createSchema({
tableName,
tableComment: undefined,
columns,
Expand All @@ -86,7 +86,7 @@ export type InsertTodo = z.infer<typeof insertTodoSchema>;`;
).toStrictEqual(result);
});

it("case3 separate = true, suffix", () => {
it("case3 separate = true, suffix", async () => {
const tableName = "todo";
const columns: Column[] = [
{
Expand Down Expand Up @@ -119,7 +119,7 @@ export type TodoInsert = z.infer<typeof todoInsertSchema>;`;
};

expect(
createSchema({
await createSchema({
tableName,
tableComment: undefined,
columns,
Expand Down
33 changes: 15 additions & 18 deletions src/process/buildSchemaText/utils/createSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,15 @@ type UpdateSchemaTextProps = {
schemaInformation: SchemaInformation;
};

export const mergeSchemaTextWithOldInformation = ({
export const mergeSchemaTextWithOldInformation = async ({
schemaName,
schemaInformation,
schemaText,
}: UpdateSchemaTextProps) => {
/* 完成したテキストからschemaInformationをつくる */

const formatted = await formatByPrettier(schemaText);
const nextSchemaInformation = pipe(
schemaText,
formatByPrettier,
formatted,
parse,
(x) => x[0] as SchemaInformation,
(x) => {
Expand Down Expand Up @@ -66,7 +65,7 @@ export const mergeSchemaTextWithOldInformation = ({
const rawNextSchemaText = schemaInformationToText(
replacedSchemaInformation,
).join("");
const formattedSchemaText = formatByPrettier(rawNextSchemaText);
const formattedSchemaText = await formatByPrettier(rawNextSchemaText);
return formattedSchemaText.trim();
};

Expand All @@ -78,14 +77,14 @@ type CreateSchemaProps = {
schemaInformationList: readonly SchemaInformation[];
mode: CreateSchemaModeUnion;
};
export const createSchema = ({
export const createSchema = async ({
tableName,
columns,
options,
tableComment,
schemaInformationList,
mode,
}: CreateSchemaProps): SchemaResult => {
}: CreateSchemaProps): Promise<SchemaResult> => {
const schemaString = columns
.map((x) =>
composeColumnStringList({ column: x, option: options, mode }).join("\n"),
Expand Down Expand Up @@ -114,7 +113,7 @@ export const createSchema = ({

const merged = G.isNullable(thisSchemaInformation)
? schemaText
: mergeSchemaTextWithOldInformation({
: await mergeSchemaTextWithOldInformation({
schemaName,
schemaText,
schemaInformation: {
Expand Down Expand Up @@ -146,16 +145,14 @@ export const createSchema = ({
/* isSeparateのとき、関数をinsert modeで再実行する */
const separeteInsertSchema =
separateSchema.isSeparate && mode === "select"
? `\n${
createSchema({
tableName,
columns,
options,
tableComment,
schemaInformationList,
mode: "insert",
}).schema
}`
? `\n${await createSchema({
tableName,
columns,
options,
tableComment,
schemaInformationList,
mode: "insert",
}).then((x) => x.schema)}`
: "";

return {
Expand Down
6 changes: 3 additions & 3 deletions src/process/buildSchemaText/utils/createSchemaFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ export const convertToColumn = (ast: any) => {
export const isCreate = (ast: AST): ast is Create =>
"create_definitions" in ast;

export const createSchemaFile = (
export const createSchemaFile = async (
tableDefinition: string[], // 0がテーブルネーム、1がテーブル定義
options: MysqlToZodOption,
schemaInformationList: readonly SchemaInformation[],
): R.Result<SchemaResult, string> => {
): Promise<R.Result<SchemaResult, string>> => {
const parser = new Parser();
const [tableName, tableDefinitionString] = tableDefinition;
if (G.isNullable(tableName) || G.isNullable(tableDefinitionString))
Expand All @@ -56,7 +56,7 @@ export const createSchemaFile = (
optionCommentsTable: options?.comments?.table,
tableName,
});
const { schema } = createSchema({
const { schema } = await createSchema({
tableName,
columns,
options,
Expand Down
4 changes: 2 additions & 2 deletions src/process/formatByPrettier.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import prettier from "@prettier/sync";
import prettier from "prettier";

export const formatByPrettier = (str: string): string =>
export const formatByPrettier = async (str: string): Promise<string> =>
prettier.format(str, {
parser: "babel-ts",
});
4 changes: 2 additions & 2 deletions src/process/outputToFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const outputToFile = async ({
output,
globalSchema,
}: OutputParams) => {
const formatted = formatByPrettier(schemaRawText);
const formatted = await formatByPrettier(schemaRawText);

const { fileName, outDir } = pipe(
output,
Expand All @@ -33,7 +33,7 @@ export const outputToFile = async ({

/* globalSchema */
if (G.isNullable(globalSchema)) return;
const globalSchemaFormatted = formatByPrettier(globalSchema);
const globalSchemaFormatted = await formatByPrettier(globalSchema);
const globalSchemaSavePath = join(process.cwd(), outDir, "globalSchema.ts");
writeFileSync(globalSchemaSavePath, globalSchemaFormatted);
console.info("\nglobalSchema file created!");
Expand Down
18 changes: 10 additions & 8 deletions test/config/rawTest2Config.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
const options = {
dbConnection: {
database: "test",
host: "localhost",
password: "test",
port: 33202,
user: "test",
"dbConnection": {
"database": "test",
"host": "localhost",
"password": "test",
"port": 32789,
"user": "test"
},
tableNames: ["posts"],
"tableNames": [
"posts"
]
};
module.exports = options;
module.exports = options;

0 comments on commit 567b9bb

Please sign in to comment.