Spaces:
Running
Running
File size: 2,251 Bytes
2e4269d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
import { env } from "$env/dynamic/private";
import { authCondition, requiresUser } from "$lib/server/auth.js";
import { collections } from "$lib/server/database.js";
import { editableToolSchema } from "$lib/server/tools/index.js";
import { generateSearchTokens } from "$lib/utils/searchTokens.js";
import { ObjectId } from "mongodb";
import { ReviewStatus } from "$lib/types/Review.js";
import { error } from "@sveltejs/kit";
import { usageLimits } from "$lib/server/usageLimits.js";
export async function POST({ request, locals }) {
if (env.COMMUNITY_TOOLS !== "true") {
error(403, "Community tools are not enabled");
}
const body = await request.json();
const parse = editableToolSchema.safeParse(body);
if (!parse.success) {
// Loop through the errors array and create a custom errors array
const errors = parse.error.errors.map((error) => {
return {
field: error.path[0],
message: error.message,
};
});
return new Response(JSON.stringify({ error: true, errors }), { status: 400 });
}
// can only create tools when logged in, IF login is setup
if (!locals.user && requiresUser) {
const errors = [{ field: "description", message: "Must be logged in. Unauthorized" }];
return new Response(JSON.stringify({ error: true, errors }), { status: 400 });
}
const toolCounts = await collections.tools.countDocuments({ createdById: locals.user?._id });
if (usageLimits?.tools && toolCounts > usageLimits.tools) {
const errors = [
{
field: "description",
message: "You have reached the maximum number of tools. Delete some to continue.",
},
];
return new Response(JSON.stringify({ error: true, errors }), { status: 400 });
}
if (!locals.user || !authCondition(locals)) {
error(401, "Unauthorized");
}
const { insertedId } = await collections.tools.insertOne({
...parse.data,
type: "community" as const,
_id: new ObjectId(),
createdById: locals.user?._id,
createdByName: locals.user?.username,
createdAt: new Date(),
updatedAt: new Date(),
last24HoursUseCount: 0,
useCount: 0,
review: ReviewStatus.PRIVATE,
searchTokens: generateSearchTokens(parse.data.displayName),
});
return new Response(JSON.stringify({ toolId: insertedId.toString() }), { status: 200 });
}
|