-
Notifications
You must be signed in to change notification settings - Fork 50
Swipehistory #168
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Swipehistory #168
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
ec16b51
feat(api): add swipe-aware foods discovery and user swipe model
nurudeenmuzainat 32c3655
test(api): cover discovery swipe exclusion behavior and docs
nurudeenmuzainat 48ec652
Merge branch 'main' into swipehistory
nurudeenmuzainat c9871d3
enforced validaity
nurudeenmuzainat 84765d7
Merge branch 'main' into swipehistory
nurudeenmuzainat File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| import { Router } from "express" | ||
| import { z } from "zod" | ||
| import { Types, type PipelineStage } from "mongoose" | ||
| import { RestaurantModel, UserSwipeModel } from "../models/index.js" | ||
|
|
||
| const querySchema = z.object({ | ||
| longitude: z.coerce.number(), | ||
| latitude: z.coerce.number(), | ||
| cursor: z.string().optional(), | ||
| user_id: z | ||
| .string() | ||
| .refine((value) => Types.ObjectId.isValid(value), "user_id must be a valid ObjectId") | ||
| .optional(), | ||
| }) | ||
|
|
||
| const PAGE_SIZE = 10 | ||
| const DISCOVERY_RADIUS_METERS = 10_000 | ||
|
|
||
| type DiscoveryRow = { | ||
| food_id: unknown | ||
| restaurant_id: unknown | ||
| food_name: string | ||
| description: string | ||
| price: number | ||
| image_url: string | ||
| restaurant_name: string | ||
| distance_meters: number | ||
| } | ||
|
|
||
| function decodeCursor(cursor?: string): number { | ||
| if (!cursor) return 0 | ||
| try { | ||
| const raw = Buffer.from(cursor, "base64").toString("utf8") | ||
| const parsed = Number(raw) | ||
| return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0 | ||
| } catch { | ||
| return 0 | ||
| } | ||
| } | ||
|
|
||
| function encodeCursor(offset: number): string { | ||
| return Buffer.from(String(offset), "utf8").toString("base64") | ||
| } | ||
|
|
||
| export const foodsRouter = Router() | ||
|
|
||
| foodsRouter.get("/discover", async (req, res, next) => { | ||
| try { | ||
| const query = querySchema.parse(req.query) | ||
| const skip = decodeCursor(query.cursor) | ||
|
|
||
| const swipedFoodIds = query.user_id | ||
| ? await UserSwipeModel.distinct("food_id", { user_id: new Types.ObjectId(query.user_id) }) | ||
| : [] | ||
|
|
||
| const pipeline: PipelineStage[] = [ | ||
| { | ||
| $geoNear: { | ||
| near: { | ||
| type: "Point", | ||
| coordinates: [query.longitude, query.latitude], | ||
| }, | ||
| distanceField: "distance_meters", | ||
| spherical: true, | ||
| maxDistance: DISCOVERY_RADIUS_METERS, | ||
| query: { is_active: true }, | ||
| }, | ||
| }, | ||
| { | ||
| $lookup: { | ||
| from: "fooditems", | ||
| localField: "_id", | ||
| foreignField: "restaurant_id", | ||
| as: "foods", | ||
| }, | ||
| }, | ||
| { $unwind: "$foods" }, | ||
| { $match: { "foods.is_active": true } }, | ||
| ...(swipedFoodIds.length > 0 | ||
| ? ([{ $match: { "foods._id": { $nin: swipedFoodIds } } }] as PipelineStage[]) | ||
| : []), | ||
| { | ||
| $project: { | ||
| food_id: "$foods._id", | ||
| restaurant_id: "$_id", | ||
| food_name: "$foods.name", | ||
| description: "$foods.description", | ||
| price: "$foods.price", | ||
| image_url: "$foods.image_url", | ||
| restaurant_name: "$name", | ||
| distance_meters: 1, | ||
| }, | ||
| }, | ||
| { $sort: { distance_meters: 1, food_id: 1 } }, | ||
| { $skip: skip }, | ||
| { $limit: PAGE_SIZE + 1 }, | ||
| ] | ||
|
|
||
| const rows = (await RestaurantModel.aggregate(pipeline)) as DiscoveryRow[] | ||
| const hasMore = rows.length > PAGE_SIZE | ||
| const items = rows.slice(0, PAGE_SIZE).map((row) => ({ | ||
| id: String(row.food_id), | ||
| restaurantId: String(row.restaurant_id), | ||
| name: row.food_name, | ||
| description: row.description, | ||
| price: row.price, | ||
| imageUrl: row.image_url, | ||
| restaurantName: row.restaurant_name, | ||
| distanceMeters: row.distance_meters, | ||
| })) | ||
|
|
||
| res.status(200).json({ | ||
| items, | ||
| cursor: hasMore ? encodeCursor(skip + PAGE_SIZE) : null, | ||
| }) | ||
| } catch (error) { | ||
| if (error instanceof z.ZodError) { | ||
| res.status(400).json({ | ||
| error: "Bad Request", | ||
| message: "Invalid query parameters", | ||
| details: error.issues.map((issue) => ({ | ||
| path: issue.path.join("."), | ||
| message: issue.message, | ||
| code: issue.code, | ||
| })), | ||
| }) | ||
| return | ||
| } | ||
| next(error) | ||
| } | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| import assert from "node:assert/strict" | ||
| import test from "node:test" | ||
| import request from "supertest" | ||
| import { RestaurantModel, UserSwipeModel } from "../src/models/index.js" | ||
| import { createApp } from "../src/app.js" | ||
|
|
||
| test("GET /api/foods/discover excludes swiped food ids when user_id is provided", async () => { | ||
| const app = createApp() | ||
|
|
||
| const originalDistinct = UserSwipeModel.distinct | ||
| const originalAggregate = RestaurantModel.aggregate | ||
|
|
||
| let capturedPipeline: Record<string, unknown>[] = [] | ||
|
|
||
| ;(UserSwipeModel.distinct as unknown as (...args: unknown[]) => Promise<unknown>) = async () => [ | ||
| "660000000000000000000500", | ||
| ] | ||
| ;(RestaurantModel.aggregate as unknown as (...args: unknown[]) => Promise<unknown>) = async ( | ||
| pipeline: Record<string, unknown>[], | ||
| ) => { | ||
| capturedPipeline = pipeline | ||
| return [] | ||
| } | ||
|
|
||
| const response = await request(app).get( | ||
| "/api/foods/discover?longitude=-73.99&latitude=40.73&user_id=660000000000000000000001", | ||
| ) | ||
|
|
||
| assert.equal(response.status, 200) | ||
| assert.ok( | ||
| capturedPipeline.some((stage) => { | ||
| const match = stage.$match as Record<string, unknown> | undefined | ||
| const foods = match?.["foods._id"] as { $nin?: unknown[] } | undefined | ||
| return Array.isArray(foods?.$nin) | ||
| }), | ||
| ) | ||
|
|
||
| UserSwipeModel.distinct = originalDistinct | ||
| RestaurantModel.aggregate = originalAggregate | ||
| }) | ||
|
|
||
| test("GET /api/foods/discover does not apply swipe exclusion without user_id", async () => { | ||
| const app = createApp() | ||
|
|
||
| const originalDistinct = UserSwipeModel.distinct | ||
| const originalAggregate = RestaurantModel.aggregate | ||
|
|
||
| let distinctCalls = 0 | ||
| let capturedPipeline: Record<string, unknown>[] = [] | ||
|
|
||
| ;(UserSwipeModel.distinct as unknown as (...args: unknown[]) => Promise<unknown>) = async () => { | ||
| distinctCalls += 1 | ||
| return [] | ||
| } | ||
| ;(RestaurantModel.aggregate as unknown as (...args: unknown[]) => Promise<unknown>) = async ( | ||
| pipeline: Record<string, unknown>[], | ||
| ) => { | ||
| capturedPipeline = pipeline | ||
| return [] | ||
| } | ||
|
|
||
| const response = await request(app).get("/api/foods/discover?longitude=-73.99&latitude=40.73") | ||
|
|
||
| assert.equal(response.status, 200) | ||
| assert.equal(distinctCalls, 0) | ||
| assert.equal( | ||
| capturedPipeline.some((stage) => { | ||
| const match = stage.$match as Record<string, unknown> | undefined | ||
| return Boolean(match?.["foods._id"]) | ||
| }), | ||
| false, | ||
| ) | ||
|
|
||
| UserSwipeModel.distinct = originalDistinct | ||
| RestaurantModel.aggregate = originalAggregate | ||
| }) | ||
|
|
||
| test("GET /api/foods/discover returns 400 when user_id is not a valid ObjectId", async () => { | ||
| const app = createApp() | ||
|
|
||
| const response = await request(app).get( | ||
| "/api/foods/discover?longitude=-73.99&latitude=40.73&user_id=invalid-id", | ||
| ) | ||
|
|
||
| assert.equal(response.status, 400) | ||
| assert.equal(response.body.error, "Bad Request") | ||
| assert.equal(response.body.message, "Invalid query parameters") | ||
| }) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
user_id must be a valid Mongo ObjectId before querying UserSwipe, please fix the discovery swipe-filter implementation for correctness and safety with emphasis on