Skip to content

Commit

Permalink
refactor: 💡 electron-trpc 替换完成
Browse files Browse the repository at this point in the history
  • Loading branch information
meetqy committed Jun 23, 2023
1 parent b196c9f commit 5bbef50
Show file tree
Hide file tree
Showing 11 changed files with 116 additions and 103 deletions.
3 changes: 2 additions & 1 deletion apps/electron/renderer/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useState } from "react";
import superjson from "superjson";

import HelloElectron from "./HelloElectron";
import Home from "./Home";
import { trpc } from "./utils/trpc";

function App() {
Expand All @@ -18,7 +19,7 @@ function App() {
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
<HelloElectron />
<Home />
</QueryClientProvider>
</trpc.Provider>
);
Expand Down
33 changes: 30 additions & 3 deletions apps/electron/renderer/src/HelloElectron.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,28 @@
import Alert from "./components/Alert";
import { trpc } from "./utils/trpc";

function HelloElectron() {
const { data } = trpc.greeting.useQuery({ name: "Electron" });
trpc.subscription.useSubscription(undefined, {
const utils = trpc.useContext();
const addLibrary = trpc.library.add.useMutation();

const chooseFolder = async () => {
const res = await window.electronAPI.library.choose();

if (!res) return Alert.open("暂时不支持此App/文件夹");

console.log(res);
console.log(addLibrary);
addLibrary.mutateAsync(res);

// if (res) {
// const f = await addLibrary.mutateAsync(res);
// console.log(f);
// // setActive(f.id);
// }
};

const { data } = trpc.base.greeting.useQuery({ name: "Electron" });
trpc.base.subscription.useSubscription(undefined, {
onData: (data) => {
console.log(data);
},
Expand All @@ -12,7 +32,14 @@ function HelloElectron() {
return null;
}

return <div>{data.text}</div>;
return (
<div>
<p>
<button onClick={chooseFolder}>选择文件夹</button>
</p>
{data.text}
</div>
);
}

export default HelloElectron;
63 changes: 49 additions & 14 deletions packages/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,53 @@
import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server";
import { EventEmitter } from "events";
import { observable } from "@trpc/server/observable";
import { z } from "zod";

import { type AppRouter } from "./src/root";
import { config } from "./src/router/config";
import { folders } from "./src/router/folder";
import { image } from "./src/router/image";
import { library } from "./src/router/library";
import { tags } from "./src/router/tags";
import { t } from "./src/trpc";

export * from "./src/root";
export { createContext } from "./src/trpc";
const ee = new EventEmitter();

/**
* Inference helpers for input types
* @example type HelloInput = RouterInputs['example']['hello']
**/
export type RouterInputs = inferRouterInputs<AppRouter>;
export * from "./src/router/library";

/**
* Inference helpers for output types
* @example type HelloOutput = RouterOutputs['example']['hello']
**/
export type RouterOutputs = inferRouterOutputs<AppRouter>;
const base = t.router({
greeting: t.procedure.input(z.object({ name: z.string() })).query((req) => {
const { input } = req;

setInterval(() => {
ee.emit("greeting", `Greeted ${input.name} ${Date.now()}`);
}, 1000);

return {
text: `Hello ${input.name}` as const,
};
}),
subscription: t.procedure.subscription(() => {
return observable((emit) => {
function onGreet(text: string) {
emit.next({ text });
}

ee.on("greeting", onGreet);

return () => {
ee.off("greeting", onGreet);
};
});
}),
});

export const appRouter = t.router({
library,
base,
tags,
image,
folders,
config,
});

// export type definition of API
export type AppRouter = typeof appRouter;
50 changes: 0 additions & 50 deletions packages/api/src/root.ts

This file was deleted.

12 changes: 7 additions & 5 deletions packages/api/src/router/config.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { z } from "zod";

import { prisma } from "@acme/db";

import { t } from "../trpc";

export const configRouter = t.router({
get: t.procedure.query(async ({ ctx }) => {
return await ctx.prisma.config.findFirst();
export const config = t.router({
get: t.procedure.query(async () => {
return await prisma.config.findFirst();
}),

update: t.procedure
Expand All @@ -15,8 +17,8 @@ export const configRouter = t.router({
webPort: z.number(),
}),
)
.mutation(async ({ ctx, input }) => {
return await ctx.prisma.config.upsert({
.mutation(async ({ input }) => {
return await prisma.config.upsert({
where: { id: "config" },
update: input,
create: {
Expand Down
7 changes: 4 additions & 3 deletions packages/api/src/router/folder.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Curd, ZodInput } from "@acme/curd";
import { prisma } from "@acme/db";

import { t } from "../trpc";

export const foldersRouter = t.router({
get: t.procedure.input(ZodInput.folder.get).query(({ ctx, input }) => {
return Curd(ctx.prisma).folder().get(input);
export const folders = t.router({
get: t.procedure.input(ZodInput.folder.get).query(({ input }) => {
return Curd(prisma).folder().get(input);
}),
});
6 changes: 3 additions & 3 deletions packages/api/src/router/image/get.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { z } from "zod";

import { CONSTANT } from "@acme/constant";
import { type Prisma } from "@acme/db";
import { prisma, type Prisma } from "@acme/db";

import { t } from "../../trpc";

Expand Down Expand Up @@ -30,7 +30,7 @@ export const get = t.procedure
orderBy: OrderByObject.optional(),
}),
)
.query(async ({ ctx, input }) => {
.query(async ({ input }) => {
const limit = input.limit ?? 20;
const { cursor, orderBy, tag, folder, keyword } = input;
const OR: Prisma.ImageWhereInput[] = [{ libraryId: typeof input.library === "number" ? input.library : undefined }, { library: { name: input.library.toString() } }];
Expand All @@ -53,7 +53,7 @@ export const get = t.procedure
});
}

const items = await ctx.prisma.image.findMany({
const items = await prisma.image.findMany({
where: {
OR,
AND,
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/router/image/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { t } from "../../trpc";
import { get } from "./get";

export const imageRouter = t.router({
export const image = t.router({
get,
});
28 changes: 15 additions & 13 deletions packages/api/src/router/library.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { z } from "zod";

import { prisma } from "@acme/db";

import { t } from "../trpc";

const LibraryAddInput = z.object({
Expand All @@ -12,17 +14,17 @@ const LibraryAddInput = z.object({

export type LibraryAdd = z.infer<typeof LibraryAddInput>;

export const libraryRouter = t.router({
get: t.procedure.query(async ({ ctx }) => {
return await ctx.prisma.library.findMany({
export const library = t.router({
get: t.procedure.query(async ({}) => {
return await prisma.library.findMany({
include: {
_count: { select: { images: true } },
},
});
}),

add: t.procedure.input(LibraryAddInput).mutation(async ({ ctx, input }) => {
return await ctx.prisma.library.create({
add: t.procedure.input(LibraryAddInput).mutation(async ({ input }) => {
return await prisma.library.create({
data: input,
});
}),
Expand All @@ -35,8 +37,8 @@ export const libraryRouter = t.router({
failCount: z.number().optional(),
}),
)
.mutation(async ({ ctx, input }) => {
return await ctx.prisma.library.update({
.mutation(async ({ input }) => {
return await prisma.library.update({
where: { id: input.id },
data: {
...input,
Expand All @@ -45,20 +47,20 @@ export const libraryRouter = t.router({
});
}),

remove: t.procedure.input(z.number()).mutation(async ({ ctx, input }) => {
await ctx.prisma.$transaction([
ctx.prisma.image.deleteMany({
remove: t.procedure.input(z.number()).mutation(async ({ input }) => {
await prisma.$transaction([
prisma.image.deleteMany({
where: { libraryId: input },
}),
ctx.prisma.folder.deleteMany({
prisma.folder.deleteMany({
where: { libraryId: input },
}),
ctx.prisma.tag.deleteMany({
prisma.tag.deleteMany({
where: { libraryId: input },
}),
]);

return await ctx.prisma.library.delete({
return await prisma.library.delete({
where: { id: input },
});
}),
Expand Down
7 changes: 4 additions & 3 deletions packages/api/src/router/tags.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Curd, ZodInput } from "@acme/curd";
import { prisma } from "@acme/db";

import { t } from "../trpc";

export const tagsRouter = t.router({
get: t.procedure.input(ZodInput.tag.get).query(({ ctx, input }) => {
return Curd(ctx.prisma).tag().get(input);
export const tags = t.router({
get: t.procedure.input(ZodInput.tag.get).query(({ input }) => {
return Curd(prisma).tag().get(input);
}),
});
8 changes: 1 addition & 7 deletions packages/api/src/trpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,7 @@ import * as trpc from "@trpc/server";
import superjson from "superjson";
import { ZodError } from "zod";

import { prisma } from "@acme/db";

export const createContext = () => {
return { prisma };
};

export const t = trpc.initTRPC.context<typeof createContext>().create({
export const t = trpc.initTRPC.create({
transformer: superjson,
errorFormatter({ shape, error }) {
return {
Expand Down

0 comments on commit 5bbef50

Please sign in to comment.