Skip to content
This repository has been archived by the owner on Oct 18, 2024. It is now read-only.

feat: ✨ fuzzy SaaS #141

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions apps/api/bronya.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ export const esbuildOptions: BuildOptions = {
path: args.path,
namespace,
}));
build.onResolve({ filter: /virtual:search/ }, (args) => ({ path: args.path, namespace }));
build.onLoad({ filter: /virtual:courses/, namespace }, async () => ({
contents: `export const courses = ${JSON.stringify(
Object.fromEntries(
Expand All @@ -133,6 +134,30 @@ export const esbuildOptions: BuildOptions = {
Object.fromEntries((await prisma.instructor.findMany()).map((x) => [x.ucinetid, x])),
)}`,
}));
build.onLoad({ filter: /virtual:search/, namespace }, async () => {
const aliases = Object.fromEntries(
(await prisma.alias.findMany()).map((x) => [x.department, x.alias]),
);
const courses = (await prisma.course.findMany()).map(normalizeCourse);
const instructors = await prisma.instructor.findMany();
return {
contents: `export const haystack = ${JSON.stringify([
...courses.flatMap((x) =>
[
x.id,
x.title,
aliases[x.department] ? `${aliases[x.department]}${x.courseNumber}` : "",
].filter((x) => x.length),
),
...instructors.flatMap((x) => [x.ucinetid, x.name]),
])}; export const mapping = ${JSON.stringify([
...courses.flatMap((x) =>
[x.id, x.id, aliases[x.department] ? x.id : ""].filter((x) => x.length),
),
...instructors.flatMap((x) => [x.ucinetid, x.ucinetid]),
])}`,
};
});
},
},
],
Expand Down
1 change: 1 addition & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"@graphql-tools/load-files": "7.0.0",
"@graphql-tools/merge": "9.0.3",
"@graphql-tools/utils": "10.1.0",
"@leeoniya/ufuzzy": "1.0.14",
"@libs/db": "workspace:^",
"@libs/lambda": "workspace:^",
"@libs/uc-irvine-lib": "workspace:^",
Expand Down
7 changes: 7 additions & 0 deletions apps/api/src/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,10 @@ declare module "virtual:instructors" {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
declare const instructors: Record<string, import("@peterportal-api/types").Instructor>;
}
/**
* Virtual module for caching the haystack and mappings for fuzzy search during build time.
*/
declare module "virtual:search" {
declare const haystack: string[];
declare const mapping: string[];
}
6 changes: 6 additions & 0 deletions apps/api/src/routes/v1/graphql/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ export const resolvers: ApolloServerOptions<BaseContext>["resolvers"] = {
instructors: proxyRestApi("/v1/rest/instructors"),
allInstructors: proxyRestApi("/v1/rest/instructors/all"),
larc: proxyRestApi("/v1/rest/larc"),
searchCourses: proxyRestApi("/v1/rest/search", {
argsTransform: (args) => ({ ...args, resultType: "course" }),
}),
searchInstructors: proxyRestApi("/v1/rest/search", {
argsTransform: (args) => ({ ...args, resultType: "instructors" }),
}),
websoc: proxyRestApi("/v1/rest/websoc", { argsTransform: geTransform }),
depts: proxyRestApi("/v1/rest/websoc/depts"),
terms: proxyRestApi("/v1/rest/websoc/terms"),
Expand Down
14 changes: 14 additions & 0 deletions apps/api/src/routes/v1/graphql/schema/search.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
type CourseSearchResult {
count: Int!
results: [Course!]!
}

type InstructorSearchResult {
count: Int!
results: [Instructor!]!
}

extend type Query {
searchCourses(query: String!, limit: Int, offset: Int): CourseSearchResult!
searchInstructors(query: String!, limit: Int, offset: Int): InstructorSearchResult!
}
11 changes: 11 additions & 0 deletions apps/api/src/routes/v1/rest/search/+config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { ApiPropsOverride } from "@bronya.js/api-construct";

import { esbuildOptions, constructs } from "../../../../../bronya.config";

export const overrides: ApiPropsOverride = {
esbuild: esbuildOptions,
constructs: {
functionPlugin: constructs.functionPlugin,
restApiProps: constructs.restApiProps,
},
};
40 changes: 40 additions & 0 deletions apps/api/src/routes/v1/rest/search/+endpoint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import uFuzzy from "@leeoniya/ufuzzy";
import { createHandler } from "@libs/lambda";
import type { Course, Instructor } from "@peterportal-api/types";
import { courses } from "virtual:courses";
import { instructors } from "virtual:instructors";
import { haystack, mapping } from "virtual:search";

import { QuerySchema } from "./schema";

const u = new uFuzzy({ intraMode: 1 /* IntraMode.SingleError */ });

export const GET = createHandler(async (event, context, res) => {
const headers = event.headers;
const requestId = context.awsRequestId;
const query = event.queryStringParameters ?? {};

const maybeParsed = QuerySchema.safeParse(query);
if (maybeParsed.success) {
const { data } = maybeParsed;
const keys = Array.from(new Set(u.search(haystack, data.query)[0]?.map((x) => mapping[x])));
const results: Array<Course | Instructor> = keys
.map((x) => courses[x] ?? instructors[x])
.filter((x) =>
!data.resultType ? x : data.resultType === "course" ? "id" in x : "ucinetid" in x,
);
return res.createOKResult(
{
count: results.length,
results: results.slice(data.offset, data.offset + data.limit),
},
headers,
requestId,
);
}
return res.createErrorResult(
400,
maybeParsed.error.issues.map((issue) => issue.message).join("; "),
requestId,
);
});
10 changes: 10 additions & 0 deletions apps/api/src/routes/v1/rest/search/schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { z } from "zod";

export const QuerySchema = z.object({
query: z.string(),
resultType: z.enum(["course", "instructor"]).optional(),
limit: z.coerce.number().int().default(10),
offset: z.coerce.number().int().default(0),
});

export type Query = z.infer<typeof QuerySchema>;
5 changes: 5 additions & 0 deletions libs/db/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ enum WebsocSectionType {

// Models

model Alias {
department String @id
alias String
}

model CalendarTerm {
year String
quarter Quarter
Expand Down
89 changes: 8 additions & 81 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading