named-query.ts 1.1 KB

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