external-user-group.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { Schema, Model, Document } from 'mongoose';
  2. import mongoosePaginate from 'mongoose-paginate-v2';
  3. import { IExternalUserGroup } from '~/features/external-user-group/interfaces/external-user-group';
  4. import UserGroup from '~/server/models/user-group';
  5. import { getOrCreateModel } from '~/server/util/mongoose-utils';
  6. export interface ExternalUserGroupDocument extends IExternalUserGroup, Document {}
  7. export interface ExternalUserGroupModel extends Model<ExternalUserGroupDocument> {
  8. [x:string]: any, // for old methods
  9. PAGE_ITEMS: 10,
  10. findGroupsWithDescendantsRecursively: (groups, descendants?) => any,
  11. }
  12. const schema = new Schema<ExternalUserGroupDocument, ExternalUserGroupModel>({
  13. name: { type: String, required: true },
  14. parent: { type: Schema.Types.ObjectId, ref: 'ExternalUserGroup', index: true },
  15. description: { type: String, default: '' },
  16. externalId: { type: String, required: true, unique: true },
  17. provider: { type: String, required: true },
  18. }, {
  19. timestamps: true,
  20. });
  21. schema.plugin(mongoosePaginate);
  22. // group name should be unique for each provider
  23. schema.index({ name: 1, provider: 1 }, { unique: true });
  24. /**
  25. * Find group that has specified externalId and update, or create one if it doesn't exist.
  26. * @param name ExternalUserGroup name
  27. * @param name ExternalUserGroup externalId
  28. * @param name ExternalUserGroup provider
  29. * @param name ExternalUserGroup description
  30. * @param name ExternalUserGroup parentId
  31. * @returns ExternalUserGroupDocument[]
  32. */
  33. schema.statics.findAndUpdateOrCreateGroup = async function(name: string, externalId: string, provider: string, description?: string, parentId?: string) {
  34. let parent: ExternalUserGroupDocument | null = null;
  35. if (parentId != null) {
  36. parent = await this.findOne({ _id: parentId });
  37. if (parent == null) {
  38. throw Error('Parent does not exist.');
  39. }
  40. }
  41. return this.findOneAndUpdate({ externalId }, {
  42. name, description, provider, parent,
  43. }, { upsert: true, new: true });
  44. };
  45. schema.statics.findWithPagination = UserGroup.findWithPagination;
  46. schema.statics.findChildrenByParentIds = UserGroup.findChildrenByParentIds;
  47. schema.statics.findGroupsWithAncestorsRecursively = UserGroup.findGroupsWithAncestorsRecursively;
  48. schema.statics.findGroupsWithDescendantsRecursively = UserGroup.findGroupsWithDescendantsRecursively;
  49. schema.statics.findGroupsWithDescendantsById = UserGroup.findGroupsWithDescendantsById;
  50. export default getOrCreateModel<ExternalUserGroupDocument, ExternalUserGroupModel>('ExternalUserGroup', schema);