Skip to content

Commit

Permalink
Merge pull request #438 from icssc/trpc-fix
Browse files Browse the repository at this point in the history
fix trpc connection
  • Loading branch information
bjsilva1 authored May 19, 2024
2 parents 7f95281 + 3a459ac commit ab96dc5
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 52 deletions.
45 changes: 31 additions & 14 deletions apps/expo/src/app/home/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ import { LinearGradient } from "tamagui/linear-gradient";

import type { MenuWithRelations } from "@zotmeal/db";
import type { PeriodName } from "@zotmeal/utils";
import { restaurantIdEnum } from "@zotmeal/db";
import {
getCurrentPeriodName,
getRestaurantNameById,
PeriodEnum,
restaurantIds,
restaurantNames,
} from "@zotmeal/utils";

Expand Down Expand Up @@ -84,8 +86,6 @@ export function EventToast() {
}

export function Home() {
// const hello = api.menu.hello.useQuery();

const { anteateryMenu, brandywineMenu, setAnteateryMenu, setBrandywineMenu } =
useMenuStore();

Expand All @@ -112,6 +112,8 @@ export function Home() {
}),
),
);
console.log(anteateryQuery);
console.log(brandywineQuery);

useEffect(() => {
if (anteateryQuery?.data) {
Expand All @@ -121,7 +123,29 @@ export function Home() {
if (brandywineQuery?.data) {
setBrandywineMenu(brandywineQuery.data);
}
}, [anteateryQuery, brandywineQuery, setAnteateryMenu, setBrandywineMenu]);

if (
anteateryQuery &&
brandywineQuery &&
anteateryQuery.isSuccess &&
brandywineQuery.isSuccess
) {
toast.show("There are 5 upcoming events.", {
// message: 'See upcoming events',
duration: 10_000_000,
burntOptions: {
shouldDismissByDrag: true,
from: "bottom",
},
});
}
}, [
anteateryQuery?.data,
brandywineQuery?.data,
setAnteateryMenu,
setBrandywineMenu,
toast,
]);

if (!anteateryQuery || !brandywineQuery) {
return <Text>Fetching menus</Text>;
Expand All @@ -142,15 +166,6 @@ export function Home() {
);
}

toast.show("There are 5 upcoming events.", {
// message: 'See upcoming events',
duration: 10_000_000,
burntOptions: {
shouldDismissByDrag: true,
from: "bottom",
},
});

return (
<RestaurantTabs>
<EventToast />
Expand Down Expand Up @@ -229,11 +244,13 @@ const PeriodPicker = ({
color,
}}
selectedValue={periodName}
onValueChange={(itemValue, _) => setPeriodName(itemValue)}
onValueChange={(itemValue, _) => {
setPeriodName(itemValue);
}}
>
{/* Create a Picker.Item for each period */}
{Object.entries(PeriodEnum).map(([period, id]) => (
<Picker.Item key={id} label={period} value={id} />
<Picker.Item key={id} label={period} value={period} />
))}
</Picker>
);
Expand Down
12 changes: 9 additions & 3 deletions apps/expo/src/utils/api.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useState } from "react";
import { Platform } from "react-native";
import Constants from "expo-constants";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { httpBatchLink, loggerLink } from "@trpc/client";
Expand All @@ -19,7 +20,7 @@ export { type RouterInputs, type RouterOutputs } from "@zotmeal/api";
*/
const getBaseUrl = () => {
/**
* Gets the IP address of your host-machine. If it cannot automatically find i t,
* Gets the IP address of your host-machine. If it cannot automatically find it,
* you'll have to manually set it. NOTE: Port 3000 should work for most but confirm
* you don't have anything else running on it, or you'd have to change it.
*
Expand All @@ -35,7 +36,12 @@ const getBaseUrl = () => {
"Failed to get localhost. Please point to your production server.",
);
}
return `http://${localhost}:3000`;

if (Platform.OS == "android") {
return `http://10.0.2.2:3000`;
}

return `http://localhost:3000`;
};

/**
Expand All @@ -49,7 +55,7 @@ export function TRPCProvider(props: { children: React.ReactNode }) {
links: [
httpBatchLink({
transformer: superjson,
url: `${getBaseUrl()}/api/trpc`,
url: getBaseUrl(),
headers() {
const headers = new Map<string, string>();
headers.set("x-trpc-source", "expo-react");
Expand Down
2 changes: 1 addition & 1 deletion apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"clean": "rm -rf .turbo node_modules",
"with-env": "dotenv -e ../../.env -- ",
"dev": "pnpm with-env sls offline --noPrependStageInUrl",
"dev": "pnpm with-env sls offline --noPrependStageInUrl --host 127.0.0.1",
"deploy": "pnpm with-env AWS_PROFILE=icssc sls deploy --stage production",
"test:daily": "pnpm with-env sls invoke local --function updateDaily | pino-pretty",
"test:weekly": "pnpm with-env sls invoke local --function getWeekly | pino-pretty"
Expand Down
15 changes: 7 additions & 8 deletions apps/server/src/functions/trpc/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@ import { APIGatewayProxyEventV2 } from "aws-lambda";

import { appRouter, createTRPCContext } from "@zotmeal/api";

const createContext = ({
event,
context,
}: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => {
const ctx = createTRPCContext({});
return { ...ctx, event, context };
const createContext = (
_opts: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>,
) => {
const headers = new Headers();
headers.set("x-trpc-source", "aws-lambda");
return createTRPCContext({ headers });
};

type Context = Awaited<ReturnType<typeof createContext>>;
// type Context = Awaited<ReturnType<typeof createContext>>;

export const handler = awsLambdaRequestHandler({
router: appRouter,
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/menus/procedures/getMenu.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { TRPCError } from "@trpc/server";
import { format } from "date-fns";
import { format, isToday, parseISO } from "date-fns";
import { describe, expect, it } from "vitest";

import { getRestaurantId } from "@zotmeal/utils";
Expand Down Expand Up @@ -54,7 +54,7 @@ describe("menu.get", () => {
restaurant: "brandywine",
});
expect(menu).toBeTruthy();
// expect(isToday(menu.date)).toBeTruthy(); // TODO: re-integrate once getMenu is fixed
expect(isToday(parseISO(menu.date))).toBeTruthy();
expect(menu.restaurantId).toEqual(getRestaurantId("brandywine"));
}, 10_000);

Expand Down
9 changes: 1 addition & 8 deletions packages/api/src/menus/router.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,7 @@
import axios from "axios";

import { createTRPCRouter, publicProcedure } from "../trpc";
import { getMenuProcedure } from "./procedures/getMenu";

const helloProcedure = publicProcedure.query(async (opts) => {
const res = await axios.get("https://jsonplaceholder.typicode.com/todos/1");
const _ = opts;
console.log(res.data);
return "menu -> hello";
});
const helloProcedure = publicProcedure.query(() => "menu -> hello");

export const menuRouter = createTRPCRouter({
get: getMenuProcedure,
Expand Down
26 changes: 25 additions & 1 deletion packages/api/src/menus/services/menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ export async function getMenu(
}

const { restaurant } = parsedParams.data;
const requestedDate = parsedParams.data.date;
const requestedPeriod = parsedParams.data.period;

// Attempt to find the restaurant
const fetchedRestaurant = await db.query.RestaurantTable.findFirst({
where: ({ name }, { eq }) => eq(name, restaurant),
});
Expand All @@ -48,7 +51,29 @@ export async function getMenu(
});
}

const requested_restaurant_id = fetchedRestaurant.id

// Attempt to find the menu
const fetchedMenu = await db.query.MenuTable.findFirst({
where: ({ date, period, restaurantId }, { eq, and }) =>
and(eq(date, requestedDate),
eq(period, requestedPeriod),
eq(restaurantId, requested_restaurant_id)),
});

if (!fetchedMenu) {
throw new TRPCError({

Check failure on line 65 in packages/api/src/menus/services/menu.ts

View workflow job for this annotation

GitHub Actions / test

src/menus/procedures/getMenu.test.ts > menu.get > should get today's brandywine lunch menu

TRPCError: menu (brandywine, lunch, 05/19/2024) not found ❯ Module.getMenu src/menus/services/menu.ts:65:11 ❯ src/menus/procedures/getMenu.ts:9:18 ❯ resolveMiddleware ../../node_modules/@trpc/server/dist/unstable-core-do-not-import/procedureBuilder.mjs:103:30 ❯ callRecursive ../../node_modules/@trpc/server/dist/unstable-core-do-not-import/procedureBuilder.mjs:153:32 ❯ callRecursive ../../node_modules/@trpc/server/dist/unstable-core-do-not-import/procedureBuilder.mjs:153:32 ❯ procedure ../../node_modules/@trpc/server/dist/unstable-core-do-not-import/procedureBuilder.mjs:183:24 ❯ ../../node_modules/@trpc/server/dist/unstable-core-do-not-import/router.mjs:111:28 ❯ src/menus/procedures/getMenu.test.ts:51:18 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Serialized Error: { code: 'NOT_FOUND' }
message: `menu (${restaurant}, ${requestedPeriod}, ${requestedDate}) not found`,
code: "NOT_FOUND",
});
}

const requestedMenuId = fetchedMenu.id

// Compile stations and dishes for the menu

const rows = await db.query.DishMenuStationJointTable.findMany({
where: ({menuId}, {eq}) => eq(menuId, requestedMenuId),
with: {
dish: {
with: {
Expand All @@ -59,7 +84,6 @@ export async function getMenu(
menu: true,
station: true,
},
limit: 5, // TODO: do findFirst with where clause instead
});

let menuResult: MenuWithRelations | null = null;
Expand Down
3 changes: 2 additions & 1 deletion packages/api/src/root.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import { eventRouter } from "./events/router";
import { menuRouter } from "./menus";
import { notificationRouter } from "./notifications/router";
import { scheduleRouter } from "./schedules/router";
import { createTRPCRouter } from "./trpc";
import { createTRPCRouter, publicProcedure } from "./trpc";

export const appRouter = createTRPCRouter({
menu: menuRouter,
event: eventRouter,
notification: notificationRouter,
schedule: scheduleRouter,
hello: publicProcedure.query(() => "Hello, world!"),
});

// export type definition of API
Expand Down
22 changes: 8 additions & 14 deletions packages/api/src/trpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
// import type { Session } from "@zotmeal/auth";
// import { auth } from "@zotmeal/auth";

import { Expo } from "expo-server-sdk";
// import { Expo } from "expo-server-sdk";
import { initTRPC } from "@trpc/server";
import superjson from "superjson";
import { ZodError } from "zod";
Expand All @@ -30,24 +30,18 @@ import { createDrizzle } from "@zotmeal/db";
* @see https://trpc.io/docs/server/context
*/

const expo: Expo = new Expo({
accessToken: process.env.EXPO_ACCESS_TOKEN,
});
// const expo: Expo = new Expo({
// accessToken: process.env.EXPO_ACCESS_TOKEN,
// });

const db = createDrizzle({ connectionString: process.env.DATABASE_URL });

export const createTRPCContext = (opts: {
headers: Headers;
// session: Session | null;
}) => {
export const createTRPCContext = (opts: { headers: Headers }) => {
const source = opts.headers.get("x-trpc-source") ?? "unknown";

console.log(">>> tRPC Request from", source, "by", "someone");
return {
...opts,
db,
expo,
};
console.log(">>> tRPC Request from", source);

return { db };
};

/**
Expand Down

0 comments on commit ab96dc5

Please sign in to comment.