# Feed API Integration Report

## Purpose

This report maps the current feed-related work to the API and client, identifies what is already present, and lists the missing pieces needed for a TikTok-style feed with posts, likes, comments, follows/friends, and user blocking.

> **Status update (2026-10-19):** The findings below describe an earlier pre-integration state. The backend now implements the For You and Following feeds, post likes and comments, follow/block, share, bookmark, hide, and report endpoints. The sibling React app is now wired to those APIs for feeds, likes, comments, following, and post-menu actions. See the current endpoint list in [README.md](./README.md); the historical “not built yet” and blocker sections below should not be treated as the current API status.

## Executive summary

There is useful groundwork in place: authenticated post routes, a post model, Zod post schemas, follow/block/friendship models, and a visibility service. The feed is not ready to connect to a front end yet. In particular, the post model, controller, and validator use different field names and data shapes; the visibility service is not used by the post controller; there is no feed endpoint; and the current CORS configuration does not permit the controller's PATCH and DELETE methods from a browser client.

**Recommended order:** first make the post contract consistent and get the existing API booting, then wire authorization/visibility and pagination, then add feed reads and social interactions, and finally add the client feed UI.

## What is already in the project

| Area | Existing work | Status |
|---|---|---|
| Authentication | Bearer-token `authenticate` middleware and `/api/auth` routes | Reusable for all feed endpoints |
| Post routes | Create, get by ID, update, delete, and list a user's posts in `src/routes/postroutes.js` | Mounted at `/api/posts`; no feed or interaction routes |
| Post controller | CRUD and author-post listing in `src/controllers/postcontroller.js` | Does not match the current post model |
| Post model | Content, visibility, moderation, counters, soft-delete timestamp, and indexes in `src/models/post.js` | Useful foundation, but controller uses a different schema contract |
| Post validation | Create/update/ID/list-query Zod schemas in `src/validators/post.shema.js` | Not attached to the post routes |
| Visibility / relationships | Block, follow, friendship models and `src/services/visibility.service.js` | Visibility helpers exist but are not called by the post controller |
| Client API helper | `client-integration/src/lib/api.js` handles bearer auth, refresh, credentials, and JSON | No feed-specific API functions or feed UI |

## Integration blockers to resolve first

1. **The post router currently prevents application startup.** `src/controllers/postcontroller.js` imports `POST_VISIBILITIES`, but `src/models/post.js` exports `VISIBILITIES`, not `POST_VISIBILITIES`. In ESM, importing a missing named export fails module loading.
2. **Post creation does not satisfy the model.** The controller writes `author`, while the model requires `authorId`. The controller reads/writes `isDeleted`, while the model uses `deletedAt`.
3. **The post payload shapes conflict.**
   - The model stores `images` as URL strings and `link` as `{ url }`.
   - The validator accepts URL strings for `images` and `link`.
   - The controller accepts a `media` array of `{ url, type }` and a string `link`.
   - The model derives `type`, but the controller validates `type` and media separately.
   These need one shared, deliberate contract before connecting a client.
4. **The validator is not wired into routes.** `validate` is used by auth routes, but none of the post routes apply `post.shema.js`. The controller's hand-written checks therefore disagree with the exported Zod rules.
5. **Visibility and blocking are not enforced consistently.** The controller's local `canViewPost` only handles public posts and the author. It does not call the existing relationship-aware `src/services/visibility.service.js`; the profile listing returns public posts only and does not apply block/follower/friend rules.
6. **The current profile-post URL differs from the suggested client URL.** It is `/api/posts/user/:userId`; this report recommends `/api/users/:userId/posts`. Pick one canonical route before implementing the client, or temporarily keep the existing route as an alias.
7. **Browser CORS does not allow post update/delete.** `src/app.js` allows only `GET`, `POST`, and `OPTIONS`, but post routes also use `PATCH` and `DELETE`. A browser preflight for these requests will fail until those methods are allowed.
8. **There is no feed endpoint or engagement API.** No controller/routes/models for feed reads, likes, or comments were found. The post model's counters describe future `Like`/`Comment` records, but those models are not present.

## Suggested API contract

Keep the current `/api/posts` base path and use the authenticated user's ID from `req.user`; never accept an author ID from the post body.

| Method | Suggested path | Purpose |
|---|---|---|
| `GET` | `/api/feed?limit=20&cursor=...` | Cursor-paginated feed of posts visible to the signed-in user |
| `POST` | `/api/posts` | Create a post |
| `GET` | `/api/posts/:postId` | Read a post only if visible to the viewer |
| `PATCH` | `/api/posts/:postId` | Edit the post's allowed fields; author only |
| `DELETE` | `/api/posts/:postId` | Soft-delete; author only |
| `GET` | `/api/users/:userId/posts?limit=20&cursor=...` | Visible posts from a profile |
| `PUT` / `DELETE` | `/api/posts/:postId/like` | Like or unlike; idempotent behavior is recommended |
| `GET` / `POST` | `/api/posts/:postId/comments` | List and create comments |
| `PATCH` / `DELETE` | `/api/comments/:commentId` | Edit/delete a comment; comment author only |
| `PUT` / `DELETE` | `/api/users/:userId/follow` | Follow or unfollow |
| `PUT` / `DELETE` | `/api/users/:userId/block` | Block or unblock |
| `POST` | `/api/users/:userId/friend-request` | Send a friend request |
| `PATCH` | `/api/friend-requests/:requestId` | Accept or reject a request |

Use a consistent response envelope, for example `{ "posts": [...], "nextCursor": "..." }` for lists and `{ "post": ... }` for a single post. Include author summary, timestamps, visibility, counts, and whether the current viewer has liked/followed where needed by the UI. Do not expose moderation/internal fields unnecessarily.

### Suggested post request shape

The existing validator and model are closest to a simple shape. Unless the client already depends on `media`, standardize on:

```json
{
  "text": "Hello campus",
  "images": ["https://example.com/image.jpg"],
  "link": "https://example.com",
  "visibility": "public"
}
```

The schema already enforces content, URL, visibility, and count rules. Decide whether images and a link may coexist; the current validator and model prohibit that. The controller should derive `type` server-side and persist `authorId`, `deletedAt`, and `editedAt` using the model's existing field names. If the front end needs a `media` array instead, update the model and validator together and document that contract.

## Suggested missing files

### Priority 0 — make existing post CRUD consistent

- `src/validators/post.schema.js` — correct the current `post.shema.js` typo when practical; retain and apply create, update, params, and list-query schemas. Add a feed query schema for `limit` and cursor validation.
- `src/controllers/postcontroller.js` — update all CRUD operations to match `Post` fields and the chosen payload contract; use the shared visibility service for reads and owner checks for writes.
- `src/routes/postroutes.js` — attach `validate(...)` to body, params, and query inputs; include the existing profile route and add the feed route once implemented.
- `src/app.js` — allow `PATCH` and `DELETE` in CORS, and mount the feed router when added; retain the existing auth middleware and error handling patterns.

### Priority 1 — feed and social interactions

- `src/models/Like.js` — unique `{ userId, postId }` record and indexes; do not trust client-supplied like counts.
- `src/models/Comment.js` — comment author, post reference, bounded text, timestamps, and soft-delete/moderation policy.
- `src/services/feed.service.js` — build a paginated, visibility-filtered feed and profile list; reuse `visibility.service.js` and exclude deleted, moderated, or blocked content according to the chosen policy.
- `src/services/post.service.js` — centralize post creation/update/delete and ownership rules if the controller otherwise grows beyond request/response mapping.
- `src/services/engagement.service.js` — like/unlike and comment operations with database-backed counts or reliable counter updates.
- `src/controllers/feed.controller.js` — feed list endpoint.
- `src/controllers/comment.controller.js` and `src/controllers/like.controller.js` — engagement endpoints.
- `src/routes/feed.routes.js` — authenticated feed endpoint; mount at `/api/feed`.
- `src/validators/comment.schema.js` and `src/validators/relationship.schema.js` — comment text, user IDs, and friend-request action validation.

### Priority 2 — expose existing relationship models

- `src/controllers/relationship.controller.js` and `src/routes/relationship.routes.js` — follow/unfollow, block/unblock, friend requests, and request acceptance/rejection using existing models.
- `src/validators/relationship.schema.js` — validate route IDs and allowed request actions.
- Integrate block changes with feed/profile/post read rules. The existing visibility service treats blocks in either direction as hiding content; preserve that behavior in all read endpoints.

### Priority 3 — client connection

- Add feed/interaction functions to `client-integration/src/lib/api.js` using its existing `api()` wrapper.
- Add a feed page and post composer, post card, comments UI, and like/follow/block controls in the consuming React app. The checked-in `client-integration` folder currently contains auth pages/components only; it is not a full front-end application.
- Configure the frontend's `VITE_API_URL` and the server's `CLIENT_ORIGINS` for the actual deployed origins.

## Validation checklist

Use the existing Zod + `validate` pattern and validate the appropriate request source:

- **Create post:** trimmed bounded text; at least text, image, or link; URL scheme limited to HTTP(S); bounded image count; valid visibility; reject/strip server-controlled fields such as `authorId`, counters, and moderation state.
- **Update post:** only explicitly editable fields; require at least one field; disallow setting author, counters, delete state, and moderation state.
- **IDs:** validate Mongo ObjectIds for post, user, and comment route params.
- **List/feed query:** integer `limit` in a bounded range (the existing post schema uses 1–50, default 20); bounded cursor with a documented encoding and stable sort (for example `createdAt` plus `_id`).
- **Comment:** non-empty trimmed text, a documented maximum length, and no server-controlled author/post IDs in the body.
- **Relationship actions:** validate target IDs and action enums; reject self-follow, self-block, and self-friend requests (the models already enforce these at persistence time).
- **Authorization:** authenticate all feed/social routes; only owners edit/delete their content; a blocked relationship must override public/follower/friend visibility.
- **Counters:** prevent duplicate likes with a unique database index; derive counts from records or update counters atomically, rather than trusting request values.

## Front-end connection sequence

1. Make the server import and start successfully with the post router mounted.
2. Set the API CORS allowlist/methods and verify `GET`, `POST`, `PATCH`, and `DELETE` browser requests with credentials and the existing bearer token flow.
3. Confirm create/read/update/delete contracts with an authenticated API client before wiring the UI.
4. Add feed pagination and verify that public, followers-only, friends-only, deleted, moderated, and blocked cases behave as intended.
5. Add like/comment/follow/block endpoints and test authorization plus duplicate-request behavior.
6. Add the React feed page and controls using the existing `api()` helper; show loading, empty, and error states and refresh feed data after mutations.

## Recommended next implementation milestone

Start with **Priority 0** and a small set of API tests for post creation, visibility, and ownership. Do not build the feed UI against the current post contract: the current route/controller/model mismatch means a client integration would be built on an API that cannot reliably create or retrieve the same post representation.
