Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

refactor(web): build /api/currency with Effect HttpApi pattern

Richie McIlroy7218d8e754b0
diff --git a/apps/web/app/api/currency/route.ts b/apps/web/app/api/currency/route.ts
index cfd8fa086..f9f5ef693 100644
--- a/apps/web/app/api/currency/route.ts
+++ b/apps/web/app/api/currency/route.ts
@@ -1,21 +1,55 @@
-import type { NextRequest } from "next/server";
+import {
+ HttpApi,
+ HttpApiBuilder,
+ HttpApiEndpoint,
+ HttpApiGroup,
+ HttpServerRequest,
+ HttpServerResponse,
+} from "@effect/platform";
+import { Effect, Layer, Schema } from "effect";
+import { apiToHandler } from "@/lib/server";
import { currencyForCountry } from "@/utils/currency";
export const dynamic = "force-dynamic";
-export async function GET(request: NextRequest) {
- const override =
- process.env.VERCEL_ENV !== "production"
- ? request.nextUrl.searchParams.get("country")
- : null;
- const country = override || request.headers.get("x-vercel-ip-country");
+const GetCurrencyParams = Schema.Struct({
+ country: Schema.optional(Schema.String),
+});
- return Response.json(
- { currency: currencyForCountry(country), country: country ?? null },
- {
- // The response varies per visitor IP, so it must never land in a shared
- // CDN cache where one region's currency would be served to another.
- headers: { "Cache-Control": "private, no-store" },
- },
- );
-}
+class Api extends HttpApi.make("CapCurrencyApi").add(
+ HttpApiGroup.make("root").add(
+ HttpApiEndpoint.get("getCurrency")`/api/currency`.setUrlParams(
+ GetCurrencyParams,
+ ),
+ ),
+) {}
+
+const ApiLive = HttpApiBuilder.api(Api).pipe(
+ Layer.provide(
+ HttpApiBuilder.group(Api, "root", (handlers) =>
+ handlers.handle("getCurrency", ({ urlParams }) =>
+ Effect.gen(function* () {
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const override =
+ process.env.VERCEL_ENV !== "production" ? urlParams.country : null;
+ const country =
+ override || request.headers["x-vercel-ip-country"] || null;
+
+ return HttpServerResponse.unsafeJson(
+ { currency: currencyForCountry(country), country },
+ {
+ // The response varies per visitor IP, so it must never land in a
+ // shared CDN cache where one region's currency would be served to
+ // another.
+ headers: { "Cache-Control": "private, no-store" },
+ },
+ );
+ }),
+ ),
+ ),
+ ),
+);
+
+const handler = apiToHandler(ApiLive);
+
+export const GET = handler;