Add new user note API endpoint

This commit is contained in:
Jesse Wierzbinski 2023-09-22 15:31:41 -10:00
parent d2d2e576a9
commit ee3d4a386f
3 changed files with 82 additions and 0 deletions

View file

@ -0,0 +1,57 @@
import { getUserByToken } from "@auth";
import { parseRequest } from "@request";
import { errorResponse, jsonResponse } from "@response";
import { MatchedRoute } from "bun";
import { Relationship } from "~database/entities/Relationship";
import { User } from "~database/entities/User";
/**
* Sets a user note
*/
export default async (
req: Request,
matchedRoute: MatchedRoute
): Promise<Response> => {
const id = matchedRoute.params.id;
// Check auth token
const token = req.headers.get("Authorization")?.split(" ")[1] || null;
if (!token)
return errorResponse("This method requires an authenticated user", 422);
const self = await getUserByToken(token);
if (!self) return errorResponse("Unauthorized", 401);
const { comment } = await parseRequest<{
comment: string;
}>(req);
const user = await User.findOneBy({
id,
});
if (!user) return errorResponse("User not found", 404);
// Check if already following
let relationship = await self.getRelationshipToOtherUser(user);
if (!relationship) {
// Create new relationship
const newRelationship = await Relationship.createNew(self, user);
self.relationships.push(newRelationship);
await self.save();
relationship = newRelationship;
}
relationship.note = comment ?? "";
// TODO: Implement duration
await relationship.save();
return jsonResponse(await relationship.toAPI());
};