models/GroupBundle.ts
2.1 KB · sha256:22bae972f475430235308d53919096020c0e636ea8bf711e626678e296494ef3
import "reflect-metadata";
import { field, model, getModel, unique, type Doc } from "../db/odm";
@model("GroupBundle")
export class GroupBundle {
@unique()
@field({ type: String, required: true, lowercase: true, trim: true })
name!: string;
@field({ type: String, default: "" })
displayName!: string;
@field({ type: [String], default: () => [] })
groups!: string[];
}
export type GroupBundleDoc = Doc<GroupBundle>;
const GroupBundleModel = getModel(GroupBundle);
export function findBundle(name: string): Promise<GroupBundleDoc | null> {
return GroupBundleModel.findOne({ name: name.toLowerCase() }).exec();
}
export function listBundles(): Promise<GroupBundleDoc[]> {
return GroupBundleModel.find().sort({ name: 1 }).exec();
}
export async function createBundle(
name: string,
opts: { displayName?: string; groups?: string[] } = {},
): Promise<GroupBundleDoc> {
if (await findBundle(name))
throw new Error(`Bundle '${name}' already exists`);
return GroupBundleModel.create({
name: name.toLowerCase(),
displayName: opts.displayName ?? name,
groups: (opts.groups ?? []).map((g) => g.toLowerCase()),
});
}
export async function deleteBundle(name: string): Promise<boolean> {
const res = await GroupBundleModel.deleteOne({
name: name.toLowerCase(),
}).exec();
return res.deletedCount > 0;
}
export async function setBundleGroups(
name: string,
groups: string[],
): Promise<GroupBundleDoc | null> {
return GroupBundleModel.findOneAndUpdate(
{ name: name.toLowerCase() },
{ groups: groups.map((g) => g.toLowerCase()) },
{ new: true },
).exec();
}
export async function addToBundle(
name: string,
group: string,
): Promise<GroupBundleDoc | null> {
return GroupBundleModel.findOneAndUpdate(
{ name: name.toLowerCase() },
{ $addToSet: { groups: group.toLowerCase() } },
{ new: true },
).exec();
}
export async function removeFromBundle(
name: string,
group: string,
): Promise<GroupBundleDoc | null> {
return GroupBundleModel.findOneAndUpdate(
{ name: name.toLowerCase() },
{ $pull: { groups: group.toLowerCase() } },
{ new: true },
).exec();
}
export { GroupBundleModel };