named-query.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. import type { Document, Model } from 'mongoose';
  3. import { Schema } from 'mongoose';
  4. import type { INamedQuery } from '~/interfaces/named-query';
  5. import { SearchDelegatorName } from '~/interfaces/named-query';
  6. import loggerFactory from '../../utils/logger';
  7. import { getOrCreateModel } from '../util/mongoose-utils';
  8. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  9. const logger = loggerFactory('growi:models:named-query');
  10. export interface NamedQueryDocument extends INamedQuery, Document {}
  11. export type NamedQueryModel = Model<NamedQueryDocument>;
  12. const schema = new Schema<NamedQueryDocument, NamedQueryModel>({
  13. name: { type: String, required: true, unique: true },
  14. aliasOf: { type: String },
  15. delegatorName: { type: String, enum: SearchDelegatorName },
  16. creator: {
  17. type: Schema.Types.ObjectId,
  18. ref: 'User',
  19. index: true,
  20. default: null,
  21. },
  22. });
  23. schema.pre('validate', async function (this, next) {
  24. if (this.aliasOf == null && this.delegatorName == null) {
  25. throw Error('Either of aliasOf and delegatorNameName must not be null.');
  26. }
  27. next();
  28. });
  29. export default getOrCreateModel<NamedQueryDocument, NamedQueryModel>(
  30. 'NamedQuery',
  31. schema,
  32. );