mirror of
https://github.com/versia-pub/server.git
synced 2026-03-13 13:59:16 +01:00
Implement account relationship endpoints
This commit is contained in:
parent
ee3d4a386f
commit
50ab0155a5
3 changed files with 96 additions and 0 deletions
60
server/api/api/v1/accounts/relationships/index.ts
Normal file
60
server/api/api/v1/accounts/relationships/index.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import { getUserByToken } from "@auth";
|
||||
import { parseRequest } from "@request";
|
||||
import { errorResponse, jsonResponse } from "@response";
|
||||
import { Relationship } from "~database/entities/Relationship";
|
||||
import { User } from "~database/entities/User";
|
||||
|
||||
/**
|
||||
* Sets a user note
|
||||
*/
|
||||
export default async (req: Request): Promise<Response> => {
|
||||
// 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 { "id[]": ids } = await parseRequest<{
|
||||
"id[]": string[];
|
||||
}>(req);
|
||||
|
||||
// Minimum id count 1, maximum 10
|
||||
if (!ids || ids.length < 1 || ids.length > 10) {
|
||||
return errorResponse("Number of ids must be between 1 and 10", 422);
|
||||
}
|
||||
|
||||
// Check if already following
|
||||
// TODO: Limit ID amount
|
||||
const relationships = (
|
||||
await Promise.all(
|
||||
ids.map(async id => {
|
||||
const user = await User.findOneBy({ id });
|
||||
if (!user) return null;
|
||||
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;
|
||||
}
|
||||
return relationship;
|
||||
})
|
||||
)
|
||||
).filter(relationship => relationship !== null) as Relationship[];
|
||||
|
||||
return jsonResponse(
|
||||
await Promise.all(relationships.map(async r => await r.toAPI()))
|
||||
);
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue