2
0

external-user-group.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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, unique: 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. /**
  23. * Find group that has specified externalId and update, or create one if it doesn't exist.
  24. * @param name ExternalUserGroup name
  25. * @param name ExternalUserGroup description
  26. * @param name ExternalUserGroup externalId
  27. * @param name ExternalUserGroup provider
  28. * @param name ExternalUserGroup parentId
  29. * @returns ExternalUserGroupDocument[]
  30. */
  31. schema.statics.findAndUpdateOrCreateGroup = async function(name, description, externalId, provider, parentId) {
  32. // create without parent
  33. if (parentId == null) {
  34. return this.findOneAndUpdate({ externalId }, { name, description, provider }, { upsert: true, new: true });
  35. }
  36. // create with parent
  37. const parent = await this.findOne({ _id: parentId });
  38. if (parent == null) {
  39. throw Error('Parent does not exist.');
  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. export default getOrCreateModel<ExternalUserGroupDocument, ExternalUserGroupModel>('ExternalUserGroup', schema);