Replace Hono with @effect/platform #2
@@ -11,11 +11,14 @@ import { WebhookReceiverRoute } from "./webhook";
|
||||
import { ZeroMutateRoute, ZeroQueryRoute } from "./zero/handler";
|
||||
import { RpcRoute } from "./rpc/handler";
|
||||
import { BASE_URL } from "@money/shared";
|
||||
import { CurrentSession, SessionMiddleware } from "./middleware/session";
|
||||
|
||||
const RootRoute = HttpLayerRouter.add(
|
||||
"GET",
|
||||
"/",
|
||||
Effect.gen(function* () {
|
||||
const d = yield* CurrentSession;
|
||||
|
||||
return HttpServerResponse.text("OK");
|
||||
}),
|
||||
);
|
||||
@@ -28,11 +31,11 @@ const AllRoutes = Layer.mergeAll(
|
||||
RpcRoute,
|
||||
WebhookReceiverRoute,
|
||||
).pipe(
|
||||
Layer.provide(SessionMiddleware.layer),
|
||||
Layer.provide(
|
||||
HttpLayerRouter.cors({
|
||||
allowedOrigins: ["https://money.koon.us", `${BASE_URL}:8081`],
|
||||
allowedMethods: ["POST", "GET", "OPTIONS"],
|
||||
// allowedHeaders: ["Content-Type", "Authorization", ""],
|
||||
credentials: true,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -1,13 +1,76 @@
|
||||
import { RpcSerialization, RpcServer } from "@effect/rpc";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
import { LinkRpcs, Link } from "@money/shared/rpc";
|
||||
import { Console, Effect, Layer, Schema } from "effect";
|
||||
import { LinkRpcs, Link, AuthMiddleware } from "@money/shared/rpc";
|
||||
import { CurrentSession } from "../middleware/session";
|
||||
import { Authorization } from "../auth/context";
|
||||
import { HttpServerRequest } from "@effect/platform";
|
||||
import { AuthSchema } from "@money/shared/auth";
|
||||
|
||||
const parseAuthorization = (input: string) =>
|
||||
Effect.gen(function* () {
|
||||
const m = /^Bearer\s+(.+)$/.exec(input);
|
||||
if (!m) {
|
||||
return yield* Effect.fail(new Error("Invalid token"));
|
||||
}
|
||||
return m[1];
|
||||
});
|
||||
|
||||
export const AuthLive = Layer.scoped(
|
||||
AuthMiddleware,
|
||||
Effect.gen(function* () {
|
||||
const auth = yield* Authorization;
|
||||
|
||||
return AuthMiddleware.of(({ headers, payload, rpc }) =>
|
||||
Effect.gen(function* () {
|
||||
const newHeaders = { ...headers };
|
||||
|
||||
const token = yield* Schema.decodeUnknown(
|
||||
Schema.Struct({
|
||||
authorization: Schema.optional(Schema.String),
|
||||
}),
|
||||
)(headers).pipe(
|
||||
// Effect.tap(Console.debug),
|
||||
Effect.flatMap(({ authorization }) =>
|
||||
authorization != undefined
|
||||
? parseAuthorization(authorization)
|
||||
: Effect.succeed(undefined),
|
||||
),
|
||||
);
|
||||
|
||||
if (token) {
|
||||
newHeaders["cookie"] = token;
|
||||
}
|
||||
|
||||
const session = yield* auth
|
||||
.use((auth) => auth.api.getSession({ headers: newHeaders }))
|
||||
.pipe(
|
||||
Effect.flatMap((s) =>
|
||||
s == null ? Effect.succeed(null) : Schema.decode(AuthSchema)(s),
|
||||
),
|
||||
Effect.tap((s) => Console.debug("Auth result", s)),
|
||||
);
|
||||
|
||||
return { auth: session };
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const LinkHandlers = LinkRpcs.toLayer({
|
||||
CreateLink: () => Effect.succeed(new Link({ href: "hi" })),
|
||||
CreateLink: () =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* CurrentSession;
|
||||
|
||||
return new Link({ href: session.auth?.user.name || "anon" });
|
||||
}),
|
||||
});
|
||||
|
||||
export const RpcRoute = RpcServer.layerHttpRouter({
|
||||
group: LinkRpcs,
|
||||
path: "/rpc",
|
||||
protocol: "http",
|
||||
}).pipe(Layer.provide(LinkHandlers), Layer.provide(RpcSerialization.layerJson));
|
||||
}).pipe(
|
||||
Layer.provide(LinkHandlers),
|
||||
Layer.provide(RpcSerialization.layerJson),
|
||||
Layer.provide(AuthLive),
|
||||
);
|
||||
|
||||
@@ -4,7 +4,7 @@ import "react-native-reanimated";
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
import { ZeroProvider } from "@rocicorp/zero/react";
|
||||
import { useMemo } from "react";
|
||||
import { authDataSchema } from "@money/shared/auth";
|
||||
import { AuthSchema } from "@money/shared/auth";
|
||||
import { Platform } from "react-native";
|
||||
import type { ZeroOptions } from "@rocicorp/zero";
|
||||
import {
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
BASE_URL,
|
||||
} from "@money/shared";
|
||||
import { expoSQLiteStoreProvider } from "@rocicorp/zero/react-native";
|
||||
import { Schema as S } from "effect";
|
||||
|
||||
export const unstable_settings = {
|
||||
anchor: "index",
|
||||
@@ -26,8 +27,8 @@ export default function RootLayout() {
|
||||
const { data: session, isPending } = authClient.useSession();
|
||||
|
||||
const authData = useMemo(() => {
|
||||
const result = authDataSchema.safeParse(session);
|
||||
return result.success ? result.data : null;
|
||||
const result = session ? S.decodeSync(AuthSchema)(session) : null;
|
||||
return result ? result : null;
|
||||
}, [session]);
|
||||
|
||||
const cookie = useMemo(() => {
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import { Button, Text, View } from "react-native";
|
||||
import { AtomRpc, useAtomSet } from "@effect-atom/atom-react";
|
||||
import { Layer } from "effect";
|
||||
import { LinkRpcs } from "@money/shared/rpc";
|
||||
import { FetchHttpClient } from "@effect/platform";
|
||||
import { RpcClient, RpcSerialization } from "@effect/rpc";
|
||||
|
||||
class Client extends AtomRpc.Tag<Client>()("RpcClient", {
|
||||
group: LinkRpcs,
|
||||
protocol: RpcClient.layerProtocolHttp({
|
||||
url: "http://laptop:3000/rpc",
|
||||
}).pipe(Layer.provide([RpcSerialization.layerJson, FetchHttpClient.layer])),
|
||||
}) {}
|
||||
|
||||
export default function Page() {
|
||||
const create = useAtomSet(Client.mutation("CreateLink"));
|
||||
|
||||
const onPress = () => {
|
||||
create({
|
||||
payload: void 0,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<View>
|
||||
<Text>RPC Test</Text>
|
||||
<Button onPress={onPress} title="Create link" />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,26 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { Schema } from "effect";
|
||||
|
||||
export const sessionSchema = z.object({
|
||||
id: z.string(),
|
||||
userId: z.string(),
|
||||
expiresAt: z.date(),
|
||||
});
|
||||
|
||||
export const userSchema = z.object({
|
||||
id: z.string(),
|
||||
email: z.string(),
|
||||
emailVerified: z.boolean(),
|
||||
name: z.string(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date(),
|
||||
});
|
||||
|
||||
export const authDataSchema = z.object({
|
||||
session: sessionSchema,
|
||||
user: userSchema,
|
||||
});
|
||||
|
||||
const DateFromDateOrString = Schema.Union(
|
||||
Schema.DateFromString,
|
||||
Schema.DateFromSelf,
|
||||
@@ -53,7 +33,3 @@ export const AuthSchema = Schema.Struct({
|
||||
});
|
||||
|
||||
export type AuthSchemaType = Schema.Schema.Type<typeof AuthSchema>;
|
||||
|
||||
export type Session = z.infer<typeof sessionSchema>;
|
||||
export type User = z.infer<typeof userSchema>;
|
||||
export type AuthData = z.infer<typeof authDataSchema>;
|
||||
|
||||
@@ -1,13 +1,29 @@
|
||||
import { Schema } from "effect";
|
||||
import { Rpc, RpcGroup } from "@effect/rpc";
|
||||
import { Context, Schema } from "effect";
|
||||
import { Rpc, RpcGroup, RpcMiddleware } from "@effect/rpc";
|
||||
import type { AuthSchema } from "./auth";
|
||||
|
||||
export class Link extends Schema.Class<Link>("Link")({
|
||||
href: Schema.String,
|
||||
}) {}
|
||||
|
||||
export class CurrentSession extends Context.Tag("CurrentSession")<
|
||||
CurrentSession,
|
||||
{ readonly auth: Schema.Schema.Type<typeof AuthSchema> | null }
|
||||
>() {}
|
||||
|
||||
export class AuthMiddleware extends RpcMiddleware.Tag<AuthMiddleware>()(
|
||||
"AuthMiddleware",
|
||||
{
|
||||
// This middleware will provide the current user context
|
||||
provides: CurrentSession,
|
||||
// This middleware requires a client implementation too
|
||||
requiredForClient: true,
|
||||
},
|
||||
) {}
|
||||
|
||||
export class LinkRpcs extends RpcGroup.make(
|
||||
Rpc.make("CreateLink", {
|
||||
success: Link,
|
||||
error: Schema.String,
|
||||
}),
|
||||
) {}
|
||||
).middleware(AuthMiddleware) {}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Transactions } from "./transactions";
|
||||
import { View, Text } from "react-native";
|
||||
import { Settings } from "./settings";
|
||||
import { useKeyboard } from "./useKeyboard";
|
||||
import type { AuthData } from "@money/shared/auth";
|
||||
import type { AuthSchemaType } from "@money/shared/auth";
|
||||
|
||||
const PAGES = {
|
||||
"/": {
|
||||
@@ -39,7 +39,7 @@ type Routes<T> = {
|
||||
export type Route = Routes<typeof PAGES>;
|
||||
|
||||
interface RouterContextType {
|
||||
auth: AuthData | null;
|
||||
auth: AuthSchemaType | null;
|
||||
route: Route;
|
||||
setRoute: (route: Route) => void;
|
||||
}
|
||||
@@ -51,7 +51,7 @@ export const RouterContext = createContext<RouterContextType>({
|
||||
});
|
||||
|
||||
type AppProps = {
|
||||
auth: AuthData | null;
|
||||
auth: AuthSchemaType | null;
|
||||
route: Route;
|
||||
setRoute: (page: Route) => void;
|
||||
};
|
||||
|
||||
50
packages/ui/src/rpc.ts
Normal file
50
packages/ui/src/rpc.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { AtomRpc } from "@effect-atom/atom-react";
|
||||
import { AuthMiddleware, LinkRpcs } from "@money/shared/rpc";
|
||||
import { FetchHttpClient, Headers } from "@effect/platform";
|
||||
import { Rpc, RpcClient, RpcMiddleware, RpcSerialization } from "@effect/rpc";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Effect } from "effect";
|
||||
import { use } from "react";
|
||||
import { RouterContext } from "./index";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import { Platform } from "react-native";
|
||||
|
||||
const protocol = RpcClient.layerProtocolHttp({
|
||||
url: "http://laptop:3000/rpc",
|
||||
}).pipe(
|
||||
Layer.provide([
|
||||
RpcSerialization.layerJson,
|
||||
FetchHttpClient.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(FetchHttpClient.RequestInit, {
|
||||
credentials: "include",
|
||||
}),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
|
||||
export const useRpc = () => {
|
||||
const { auth } = use(RouterContext);
|
||||
|
||||
return class Client extends AtomRpc.Tag<Client>()("RpcClient", {
|
||||
group: LinkRpcs,
|
||||
protocol: Layer.merge(
|
||||
protocol,
|
||||
RpcMiddleware.layerClient(AuthMiddleware, ({ request }) =>
|
||||
Effect.succeed({
|
||||
...request,
|
||||
...(auth && Platform.OS == ("TUI" as any)
|
||||
? {
|
||||
headers: Headers.set(
|
||||
request.headers,
|
||||
"authorization",
|
||||
"Bearer " + Redacted.value(auth.session.token),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
}) {};
|
||||
};
|
||||
@@ -7,6 +7,9 @@ import { useKeyboard } from "../useKeyboard";
|
||||
import { Button } from "../../components/Button";
|
||||
import * as Table from "../../components/Table";
|
||||
import * as Dialog from "../../components/Dialog";
|
||||
import { useAtomSet } from "@effect-atom/atom-react";
|
||||
import { useRpc } from "../rpc";
|
||||
import * as Exit from "effect/Exit";
|
||||
|
||||
const COLUMNS: Table.Column[] = [
|
||||
{ name: "name", label: "Name" },
|
||||
@@ -116,52 +119,79 @@ export function Accounts() {
|
||||
}
|
||||
|
||||
function AddAccount() {
|
||||
const { auth } = use(RouterContext);
|
||||
const [link, details] = useQuery(queries.getPlaidLink(auth));
|
||||
const rpc = useRpc();
|
||||
const createLink = useAtomSet(rpc.mutation("CreateLink"), {
|
||||
mode: "promiseExit",
|
||||
});
|
||||
|
||||
const [href, setHref] = useState("");
|
||||
|
||||
// const [link, details] = useQuery(queries.getPlaidLink(auth));
|
||||
const { close } = use(Dialog.Context);
|
||||
|
||||
const openLink = () => {
|
||||
if (!link) return;
|
||||
Linking.openURL(link.link);
|
||||
const init = () => {
|
||||
console.log("INIT");
|
||||
const p = createLink({ payload: void 0 })
|
||||
.then((link) => {
|
||||
console.log("my link", link);
|
||||
if (Exit.isSuccess(link)) {
|
||||
setHref(link.value.href);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
console.log("WHAT");
|
||||
});
|
||||
console.log(p);
|
||||
};
|
||||
|
||||
const z = useZero<Schema, Mutators>();
|
||||
|
||||
useEffect(() => {
|
||||
console.log(link, details);
|
||||
if (details.type != "complete") return;
|
||||
if (link != undefined) {
|
||||
if (!link.completeAt) {
|
||||
const timer = setInterval(() => {
|
||||
console.log("Checking for link");
|
||||
z.mutate.link.get({ link_token: link.token });
|
||||
}, 1000 * 5);
|
||||
return () => clearInterval(timer);
|
||||
} else {
|
||||
if (close) close();
|
||||
return;
|
||||
}
|
||||
}
|
||||
console.log("Creating new link");
|
||||
z.mutate.link.create();
|
||||
}, [link, details]);
|
||||
console.log("useEffect");
|
||||
init();
|
||||
}, []);
|
||||
|
||||
// const openLink = () => {
|
||||
// if (!link) return;
|
||||
// Linking.openURL(link.link);
|
||||
// };
|
||||
|
||||
// const z = useZero<Schema, Mutators>();
|
||||
|
||||
// useEffect(() => {
|
||||
// console.log(link, details);
|
||||
// if (details.type != "complete") return;
|
||||
// if (link != undefined) {
|
||||
// if (!link.completeAt) {
|
||||
// const timer = setInterval(() => {
|
||||
// console.log("Checking for link");
|
||||
// z.mutate.link.get({ link_token: link.token });
|
||||
// }, 1000 * 5);
|
||||
// return () => clearInterval(timer);
|
||||
// } else {
|
||||
// if (close) close();
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
// console.log("Creating new link");
|
||||
// z.mutate.link.create();
|
||||
// }, [link, details]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Text>Href: {href}</Text>
|
||||
<Button onPress={() => close && close()}>close</Button>
|
||||
{link ? (
|
||||
<>
|
||||
<Text style={{ fontFamily: "mono" }}>
|
||||
Please click the button to complete setup.
|
||||
</Text>
|
||||
|
||||
<Button shortcut="return" onPress={openLink}>
|
||||
Open Plaid
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Text style={{ fontFamily: "mono" }}>Loading Plaid Link</Text>
|
||||
)}
|
||||
{/* {link ? ( */}
|
||||
{/* <> */}
|
||||
{/* <Text style={{ fontFamily: "mono" }}> */}
|
||||
{/* Please click the button to complete setup. */}
|
||||
{/* </Text> */}
|
||||
{/**/}
|
||||
{/* <Button shortcut="return" onPress={openLink}> */}
|
||||
{/* Open Plaid */}
|
||||
{/* </Button> */}
|
||||
{/* </> */}
|
||||
{/* ) : ( */}
|
||||
{/* <Text style={{ fontFamily: "mono" }}>Loading Plaid Link</Text> */}
|
||||
{/* )} */}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user