@ewb/mongoose-query-express 1.1.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,31 +1,3 @@
1
- /// <reference types="mongoose/types/document.js" />
2
- /// <reference types="mongoose/types/types.js" />
3
- /// <reference types="mongoose/types/query.js" />
4
- /// <reference types="mongoose/types/aggregate.js" />
5
- /// <reference types="mongoose/types/callback.js" />
6
- /// <reference types="mongoose/types/collection.js" />
7
- /// <reference types="mongoose/types/connection.js" />
8
- /// <reference types="mongoose/types/cursor.js" />
9
- /// <reference types="mongoose/types/document.js" />
10
- /// <reference types="mongoose/types/error.js" />
11
- /// <reference types="mongoose/types/expressions.js" />
12
- /// <reference types="mongoose/types/helpers.js" />
13
- /// <reference types="mongoose/types/middlewares.js" />
14
- /// <reference types="mongoose/types/indexes.js" />
15
- /// <reference types="mongoose/types/models.js" />
16
- /// <reference types="mongoose/types/mongooseoptions.js" />
17
- /// <reference types="mongoose/types/pipelinestage.js" />
18
- /// <reference types="mongoose/types/populate.js" />
19
- /// <reference types="mongoose/types/query.js" />
20
- /// <reference types="mongoose/types/schemaoptions.js" />
21
- /// <reference types="mongoose/types/schematypes.js" />
22
- /// <reference types="mongoose/types/session.js" />
23
- /// <reference types="mongoose/types/types.js" />
24
- /// <reference types="mongoose/types/utility.js" />
25
- /// <reference types="mongoose/types/validation.js" />
26
- /// <reference types="mongoose/types/virtuals.js" />
27
- /// <reference types="mongoose/types/inferrawdoctype.js" />
28
- /// <reference types="mongoose/types/inferschematype.js" />
29
1
  import { ISearchPaginate, Query, QueryModel } from '@ewb/mongoose-query';
30
2
  import { NextFunction, Request, Response } from 'express';
31
3
  import mongoose from 'mongoose';
@@ -45,14 +17,16 @@ export interface IQueryExpressHandlerOptions<R extends Request, T extends object
45
17
  interface BulkProps {
46
18
  runNext?: boolean;
47
19
  }
48
- export declare class QueryExpress<R extends Request, T extends mongoose.Document<mongoose.Types.ObjectId>> {
20
+ export declare class QueryExpress<R extends Request, DocType extends object, T extends mongoose.HydratedDocument<DocType> & {
21
+ _id: mongoose.Types.ObjectId;
22
+ }> {
49
23
  private param;
50
24
  private handler;
51
25
  readonly options: IQueryExpressHandlerOptions<R, T>;
52
- constructor(param: keyof R, handler: QueryModel<T>, options?: IQueryExpressHandlerOptions<R, T>);
26
+ constructor(param: keyof R, handler: QueryModel<DocType>, options?: IQueryExpressHandlerOptions<R, T>);
53
27
  post(req: R, res: Response, next: NextFunction): Promise<void>;
54
- findOne(req: R, res: Response, next: NextFunction): Promise<void>;
55
- search(req: R, res: Response, next: NextFunction): Promise<void | Response<any, Record<string, any>>>;
28
+ findOne(req: R, _res: Response, next: NextFunction): Promise<void>;
29
+ search(req: R, res: Response, next: NextFunction, asArray?: boolean): Promise<void | Response<any, Record<string, any>>>;
56
30
  searchNext(req: R, res: Response, next: NextFunction): Promise<void>;
57
31
  private _search;
58
32
  export(req: R, res: Response, next: NextFunction): Promise<void>;
@@ -63,11 +37,11 @@ export declare class QueryExpress<R extends Request, T extends mongoose.Document
63
37
  bulkPatch(req: R, res: Response, next: NextFunction): Promise<void | Response<any, Record<string, any>>>;
64
38
  bulkDelete({ runNext }: BulkProps): (req: R, res: Response, next: NextFunction) => Promise<void>;
65
39
  bulkArchive({ runNext }: BulkProps): (req: R, res: Response, next: NextFunction) => Promise<void>;
66
- addToNextQuery(fn: (req: R) => mongoose.FilterQuery<T> | null): (req: R, _: Response, next: NextFunction) => void;
40
+ addToNextQuery(fn: (req: R) => mongoose.QueryFilter<T> | null): (req: R, _: Response, next: NextFunction) => void;
67
41
  subRoute(req: R, _res: Response, next: NextFunction): void;
68
- subDoc<R2 extends keyof R, P extends keyof T>(reqKey: R2, subArrayKey: P): QueryExpressSub<R, T, P>;
42
+ subDoc<R2 extends keyof R, P extends keyof DocType>(reqKey: R2, subArrayKey: P): QueryExpressSub<R, DocType, P, T>;
69
43
  addRootRequest(req: R): void;
70
- getRootQuery(req: R): mongoose.FilterQuery<T>;
44
+ getRootQuery(req: R): mongoose.QueryFilter<T>;
71
45
  removeRootRequest(req: R, slugKey?: string): void;
72
46
  addToQuery(req: R, _res: Response, next: NextFunction): void;
73
47
  addToPost(req: R, _res: Response, next: NextFunction): void;
@@ -75,7 +49,7 @@ export declare class QueryExpress<R extends Request, T extends mongoose.Document
75
49
  preHistory(req: R): void;
76
50
  postHistory(req: R, fetchNew?: boolean): Promise<void>;
77
51
  init(req: R): void;
78
- query(req: R): Query<T, object, import("@ewb/mongoose-query").IMongooseQueryOptions>;
52
+ query(req: R): Query<DocType>;
79
53
  pageLinkHeader(req: R, data: ISearchPaginate<any>): string;
80
54
  private getDoc;
81
55
  private getFindOpts;
@@ -1,5 +1,5 @@
1
1
  import { getPageLinkHeader, QueryError, } from '@ewb/mongoose-query';
2
- import httpStatus from 'http-status';
2
+ import status from 'http-status';
3
3
  import mongoose from 'mongoose';
4
4
  import { QueryExpressSub } from './QueryExpressSub.js';
5
5
  export class QueryExpress {
@@ -46,7 +46,7 @@ export class QueryExpress {
46
46
  next(QueryError.catch(e));
47
47
  }
48
48
  }
49
- async findOne(req, res, next) {
49
+ async findOne(req, _res, next) {
50
50
  try {
51
51
  if (this.skipHandlerAction(req, 'findOne')) {
52
52
  req.ewb.queryOptions.skipHandlerAction = undefined;
@@ -65,13 +65,13 @@ export class QueryExpress {
65
65
  next(QueryError.catch(e));
66
66
  }
67
67
  }
68
- async search(req, res, next) {
68
+ async search(req, res, next, asArray = false) {
69
69
  try {
70
70
  if (this.skipHandlerAction(req, 'search')) {
71
71
  return next();
72
72
  }
73
73
  const data = await this._search(req, res);
74
- if (req.query.as === 'array' || this.query(req).page > 0) {
74
+ if (asArray || req.query.as === 'array' || this.query(req).page > 0) {
75
75
  return res.json(data.data);
76
76
  }
77
77
  return res.json(data);
@@ -189,8 +189,7 @@ export class QueryExpress {
189
189
  await this.handler.updateMany(this.query(req).root || {}, ids, req.body);
190
190
  this.query(req).addRoot({ _id: { $in: ids } });
191
191
  this.query(req).setSkipAndLimit(0, ids.length);
192
- req.query.as = 'array';
193
- return this.search(req, res, next);
192
+ return this.search(req, res, next, true);
194
193
  }
195
194
  catch (e) {
196
195
  next(QueryError.catch(e));
@@ -279,7 +278,7 @@ export class QueryExpress {
279
278
  if (this.options.slugKey) {
280
279
  return { [this.options.slugKey]: param };
281
280
  }
282
- throw new QueryError(httpStatus.BAD_REQUEST, `Param is not valid`, {
281
+ throw new QueryError(status.BAD_REQUEST, `Param is not valid`, {
283
282
  detail: 'Need to be of type MongoDB ObjectID',
284
283
  });
285
284
  }
@@ -314,12 +313,13 @@ export class QueryExpress {
314
313
  if (req[param]) {
315
314
  return this.getDoc(req, param)._id.toHexString();
316
315
  }
317
- if (!req.params[param]) {
318
- throw new QueryError(httpStatus.BAD_REQUEST, String(param), {
316
+ const value = req.params[param];
317
+ if (typeof value !== 'string' || !value) {
318
+ throw new QueryError(status.BAD_REQUEST, String(param), {
319
319
  detail: 'Param is not valid',
320
320
  });
321
321
  }
322
- return req.params[param];
322
+ return value;
323
323
  }
324
324
  preHistory(req) {
325
325
  if (this.options.history?.active && req.ewb.queryHistory) {
@@ -354,7 +354,7 @@ export class QueryExpress {
354
354
  return req[this.options.queryKey];
355
355
  }
356
356
  if (!req.ewb.query) {
357
- throw new QueryError(httpStatus.INTERNAL_SERVER_ERROR, 'Query not init', {
357
+ throw new QueryError(status.INTERNAL_SERVER_ERROR, 'Query not init', {
358
358
  detail: `ewb.query missing or queryKey option missing in QueryExpress ${String(this.param)}`,
359
359
  });
360
360
  }
@@ -375,14 +375,14 @@ export class QueryExpress {
375
375
  }
376
376
  validateReq(req) {
377
377
  if (!req[this.param]) {
378
- throw new QueryError(httpStatus.NOT_FOUND, String(this.param), {
378
+ throw new QueryError(status.NOT_FOUND, String(this.param), {
379
379
  detail: 'Param is not valid',
380
380
  });
381
381
  }
382
382
  }
383
383
  validateIdsInBody(req) {
384
384
  if (!req.body.ids) {
385
- throw new QueryError(httpStatus.BAD_REQUEST, 'ids', {
385
+ throw new QueryError(status.BAD_REQUEST, 'ids', {
386
386
  detail: 'ids is required',
387
387
  });
388
388
  }
@@ -1,40 +1,15 @@
1
- /// <reference types="mongoose/types/document.js" />
2
- /// <reference types="mongoose/types/types.js" />
3
- /// <reference types="mongoose/types/aggregate.js" />
4
- /// <reference types="mongoose/types/callback.js" />
5
- /// <reference types="mongoose/types/collection.js" />
6
- /// <reference types="mongoose/types/connection.js" />
7
- /// <reference types="mongoose/types/cursor.js" />
8
- /// <reference types="mongoose/types/document.js" />
9
- /// <reference types="mongoose/types/error.js" />
10
- /// <reference types="mongoose/types/expressions.js" />
11
- /// <reference types="mongoose/types/helpers.js" />
12
- /// <reference types="mongoose/types/middlewares.js" />
13
- /// <reference types="mongoose/types/indexes.js" />
14
- /// <reference types="mongoose/types/models.js" />
15
- /// <reference types="mongoose/types/mongooseoptions.js" />
16
- /// <reference types="mongoose/types/pipelinestage.js" />
17
- /// <reference types="mongoose/types/populate.js" />
18
- /// <reference types="mongoose/types/query.js" />
19
- /// <reference types="mongoose/types/schemaoptions.js" />
20
- /// <reference types="mongoose/types/schematypes.js" />
21
- /// <reference types="mongoose/types/session.js" />
22
- /// <reference types="mongoose/types/types.js" />
23
- /// <reference types="mongoose/types/utility.js" />
24
- /// <reference types="mongoose/types/validation.js" />
25
- /// <reference types="mongoose/types/virtuals.js" />
26
- /// <reference types="mongoose/types/inferrawdoctype.js" />
27
- /// <reference types="mongoose/types/inferschematype.js" />
28
1
  import { QueryModel } from '@ewb/mongoose-query';
29
2
  import { NextFunction, Request, Response } from 'express';
30
3
  import mongoose from 'mongoose';
31
4
  import { QueryExpress } from './QueryExpress.js';
32
- export declare class QueryExpressSub<R extends Request, T extends mongoose.Document<mongoose.Types.ObjectId>, K extends keyof T> {
5
+ export declare class QueryExpressSub<R extends Request, DocType extends object, K extends keyof DocType, T extends mongoose.HydratedDocument<DocType> & {
6
+ _id: mongoose.Types.ObjectId;
7
+ }> {
33
8
  private handler;
34
9
  private express;
35
10
  private param;
36
11
  private subKey;
37
- constructor(handler: QueryModel<T>, express: QueryExpress<R, T>, param: keyof R, subKey: K);
12
+ constructor(handler: QueryModel<DocType>, express: QueryExpress<R, DocType, T>, param: keyof R, subKey: K);
38
13
  post(req: R, _res: Response, next: NextFunction): Promise<void>;
39
14
  search(req: R, res: Response, next: NextFunction): Promise<Response<any, Record<string, any>>>;
40
15
  findOne(req: R, _res: Response, next: NextFunction): Promise<void>;
@@ -1,5 +1,5 @@
1
1
  import { QueryError } from '@ewb/mongoose-query';
2
- import httpStatus from 'http-status';
2
+ import status from 'http-status';
3
3
  import mongoose from 'mongoose';
4
4
  export class QueryExpressSub {
5
5
  constructor(handler, express, param, subKey) {
@@ -97,7 +97,7 @@ export class QueryExpressSub {
97
97
  }
98
98
  validateReq(req) {
99
99
  if (!req[this.param]) {
100
- throw new QueryError(httpStatus.NOT_FOUND, 'Document not found', {
100
+ throw new QueryError(status.NOT_FOUND, 'Document not found', {
101
101
  detail: `Param ${String(this.param)} not found`,
102
102
  });
103
103
  }
@@ -0,0 +1,60 @@
1
+ import { ISearchPaginate, Query, QueryModel } from '@ewb/mongoose-query';
2
+ import { NextFunction, Request, Response } from 'express';
3
+ import mongoose from 'mongoose';
4
+ import { QueryExpressSub } from './QueryExpressSub.js';
5
+ export interface IQueryExpressOptions {
6
+ skipHandlerAction?: 'post' | 'patch' | 'archive' | 'findOne' | 'search' | 'delete' | 'export';
7
+ }
8
+ export interface IQueryExpressHandlerOptions<R extends Request, T extends object> {
9
+ queryKey?: keyof R;
10
+ slugKey?: keyof T & string;
11
+ archiveKey?: keyof T;
12
+ history?: {
13
+ active: boolean;
14
+ ignoreFields?: (keyof T)[];
15
+ };
16
+ }
17
+ interface BulkProps {
18
+ runNext?: boolean;
19
+ }
20
+ export declare class QueryExpress<R extends Request, DocType extends object, T extends mongoose.HydratedDocument<DocType, {
21
+ _id: mongoose.Types.ObjectId;
22
+ }>> {
23
+ private param;
24
+ private handler;
25
+ readonly options: IQueryExpressHandlerOptions<R, T>;
26
+ constructor(param: keyof R, handler: QueryModel<DocType>, options?: IQueryExpressHandlerOptions<R, T>);
27
+ post(req: R, res: Response, next: NextFunction): Promise<void>;
28
+ findOne(req: R, _res: Response, next: NextFunction): Promise<void>;
29
+ search(req: R, res: Response, next: NextFunction): Promise<void | Response<any, Record<string, any>>>;
30
+ searchNext(req: R, res: Response, next: NextFunction): Promise<void>;
31
+ private _search;
32
+ export(req: R, res: Response, next: NextFunction): Promise<void>;
33
+ patch(req: R, _res: Response, next: NextFunction): Promise<void>;
34
+ archive(req: R, _res: Response, next: NextFunction): Promise<void>;
35
+ delete(req: R, _res: Response, next: NextFunction): Promise<void>;
36
+ json(req: R, res: Response, next: NextFunction): Promise<Response<any, Record<string, any>>>;
37
+ bulkPatch(req: R, res: Response, next: NextFunction): Promise<void | Response<any, Record<string, any>>>;
38
+ bulkDelete({ runNext }: BulkProps): (req: R, res: Response, next: NextFunction) => Promise<void>;
39
+ bulkArchive({ runNext }: BulkProps): (req: R, res: Response, next: NextFunction) => Promise<void>;
40
+ addToNextQuery(fn: (req: R) => mongoose.FilterQuery<T> | null): (req: R, _: Response, next: NextFunction) => void;
41
+ subRoute(req: R, _res: Response, next: NextFunction): void;
42
+ subDoc<R2 extends keyof R, P extends keyof DocType>(reqKey: R2, subArrayKey: P): QueryExpressSub<R, DocType, P, T>;
43
+ addRootRequest(req: R): void;
44
+ getRootQuery(req: R): mongoose.FilterQuery<T>;
45
+ removeRootRequest(req: R, slugKey?: string): void;
46
+ addToQuery(req: R, _res: Response, next: NextFunction): void;
47
+ addToPost(req: R, _res: Response, next: NextFunction): void;
48
+ getParam(req: R, param?: keyof R): any;
49
+ preHistory(req: R): void;
50
+ postHistory(req: R, fetchNew?: boolean): Promise<void>;
51
+ init(req: R): void;
52
+ query(req: R): Query<DocType>;
53
+ pageLinkHeader(req: R, data: ISearchPaginate<any>): string;
54
+ private getDoc;
55
+ private getFindOpts;
56
+ private validateReq;
57
+ private validateIdsInBody;
58
+ private skipHandlerAction;
59
+ }
60
+ export {};
@@ -0,0 +1,398 @@
1
+ import { getPageLinkHeader, QueryError, } from '@ewb/mongoose-query';
2
+ import status from 'http-status';
3
+ import mongoose from 'mongoose';
4
+ import { QueryExpressSub } from './QueryExpressSub.js';
5
+ export class QueryExpress {
6
+ constructor(param, handler, options = {}) {
7
+ this.param = param;
8
+ this.handler = handler;
9
+ this.options = options;
10
+ this.post = this.post.bind(this);
11
+ this.findOne = this.findOne.bind(this);
12
+ this.search = this.search.bind(this);
13
+ this.searchNext = this.searchNext.bind(this);
14
+ this._search = this._search.bind(this);
15
+ this.export = this.export.bind(this);
16
+ this.patch = this.patch.bind(this);
17
+ this.archive = this.archive.bind(this);
18
+ this.delete = this.delete.bind(this);
19
+ this.json = this.json.bind(this);
20
+ this.bulkPatch = this.bulkPatch.bind(this);
21
+ this.bulkDelete = this.bulkDelete.bind(this);
22
+ this.bulkArchive = this.bulkArchive.bind(this);
23
+ this.subRoute = this.subRoute.bind(this);
24
+ this.addToQuery = this.addToQuery.bind(this);
25
+ this.addToPost = this.addToPost.bind(this);
26
+ this.getDoc = this.getDoc.bind(this);
27
+ this.preHistory = this.preHistory.bind(this);
28
+ }
29
+ async post(req, res, next) {
30
+ try {
31
+ if (this.skipHandlerAction(req, 'post')) {
32
+ return next();
33
+ }
34
+ this.init(req);
35
+ if (req.ewb.queryPostBody) {
36
+ for (const key in req.ewb.queryPostBody) {
37
+ req.body[key] = req.ewb.queryPostBody[key];
38
+ }
39
+ }
40
+ req[this.param] = (await this.handler.create(req.body));
41
+ await this.handler.populate(this.query(req), this.getDoc(req), 'onPost');
42
+ res.status(201);
43
+ next();
44
+ }
45
+ catch (e) {
46
+ next(QueryError.catch(e));
47
+ }
48
+ }
49
+ async findOne(req, _res, next) {
50
+ try {
51
+ if (this.skipHandlerAction(req, 'findOne')) {
52
+ req.ewb.queryOptions.skipHandlerAction = undefined;
53
+ return next();
54
+ }
55
+ this.init(req);
56
+ this.addRootRequest(req);
57
+ req[this.param] = (await this.handler.findOne(this.query(req), this.getFindOpts(req)));
58
+ this.preHistory(req);
59
+ this.removeRootRequest(req, this.options.slugKey);
60
+ this.validateReq(req);
61
+ await this.handler.populate(this.query(req), this.getDoc(req), 'onFindOne');
62
+ next();
63
+ }
64
+ catch (e) {
65
+ next(QueryError.catch(e));
66
+ }
67
+ }
68
+ async search(req, res, next) {
69
+ try {
70
+ if (this.skipHandlerAction(req, 'search')) {
71
+ return next();
72
+ }
73
+ const data = await this._search(req, res);
74
+ if (req.query.as === 'array' || this.query(req).page > 0) {
75
+ return res.json(data.data);
76
+ }
77
+ return res.json(data);
78
+ }
79
+ catch (e) {
80
+ next(QueryError.catch(e));
81
+ }
82
+ }
83
+ async searchNext(req, res, next) {
84
+ try {
85
+ if (this.skipHandlerAction(req, 'search')) {
86
+ return next();
87
+ }
88
+ req.ewb.querySearchJson = await this._search(req, res);
89
+ next();
90
+ }
91
+ catch (e) {
92
+ next(QueryError.catch(e));
93
+ }
94
+ }
95
+ async _search(req, res) {
96
+ this.init(req);
97
+ this.query(req).removeQuery('as');
98
+ const data = await this.handler.search(this.query(req));
99
+ res.setHeader('Link', this.pageLinkHeader(req, data));
100
+ res.setHeader('X-Total-Count', data.count);
101
+ return data;
102
+ }
103
+ async export(req, res, next) {
104
+ try {
105
+ if (this.skipHandlerAction(req, 'export')) {
106
+ return next();
107
+ }
108
+ this.init(req);
109
+ this.query(req).export = true;
110
+ const paginate = await this.handler.search(this.query(req));
111
+ res.setHeader('Link', this.pageLinkHeader(req, paginate));
112
+ res.setHeader('X-Total-Count', paginate.count);
113
+ req.ewb.queryExportJson = paginate.data;
114
+ next();
115
+ }
116
+ catch (e) {
117
+ next(QueryError.catch(e));
118
+ }
119
+ }
120
+ async patch(req, _res, next) {
121
+ try {
122
+ if (this.skipHandlerAction(req, 'patch')) {
123
+ return next();
124
+ }
125
+ this.validateReq(req);
126
+ this.init(req);
127
+ const query = this.query(req);
128
+ req[this.param] = (await this.handler.findOneAndUpdate(query, { _id: this.getDoc(req)._id }, { $set: req.body }));
129
+ this.postHistory(req).then();
130
+ await this.handler.populate(this.query(req), this.getDoc(req), 'onPatch');
131
+ next();
132
+ }
133
+ catch (e) {
134
+ next(QueryError.catch(e));
135
+ }
136
+ }
137
+ async archive(req, _res, next) {
138
+ try {
139
+ if (this.skipHandlerAction(req, 'archive')) {
140
+ return next();
141
+ }
142
+ this.validateReq(req);
143
+ this.init(req);
144
+ req[this.param] = (await this.handler.findOneAndUpdate(this.query(req), { _id: this.getDoc(req)._id }, { [this.options.archiveKey]: true }));
145
+ this.postHistory(req).then();
146
+ next();
147
+ }
148
+ catch (e) {
149
+ next(QueryError.catch(e));
150
+ }
151
+ }
152
+ async delete(req, _res, next) {
153
+ try {
154
+ if (this.skipHandlerAction(req, 'delete')) {
155
+ return next();
156
+ }
157
+ this.validateReq(req);
158
+ this.init(req);
159
+ await this.handler.deleteOne({ _id: this.getDoc(req)._id });
160
+ next();
161
+ }
162
+ catch (e) {
163
+ next(QueryError.catch(e));
164
+ }
165
+ }
166
+ async json(req, res, next) {
167
+ try {
168
+ this.validateReq(req);
169
+ const ret = await this.handler.json(req[this.param]);
170
+ if (typeof req.query.select === 'string') {
171
+ const newRet = {};
172
+ const selectArray = req.query.select.split(',');
173
+ for (const key of selectArray) {
174
+ newRet[key] = ret[key];
175
+ }
176
+ return res.json(newRet);
177
+ }
178
+ res.json(ret);
179
+ }
180
+ catch (e) {
181
+ next(QueryError.catch(e));
182
+ }
183
+ }
184
+ async bulkPatch(req, res, next) {
185
+ try {
186
+ const ids = this.validateIdsInBody(req);
187
+ delete req.body.ids;
188
+ this.init(req);
189
+ await this.handler.updateMany(this.query(req).root || {}, ids, req.body);
190
+ this.query(req).addRoot({ _id: { $in: ids } });
191
+ this.query(req).setSkipAndLimit(0, ids.length);
192
+ req.query.as = 'array';
193
+ return this.search(req, res, next);
194
+ }
195
+ catch (e) {
196
+ next(QueryError.catch(e));
197
+ }
198
+ }
199
+ bulkDelete({ runNext }) {
200
+ return async (req, res, next) => {
201
+ try {
202
+ const ids = this.validateIdsInBody(req);
203
+ this.init(req);
204
+ const deleted = await this.handler.deleteMany(this.query(req).root || {}, ids);
205
+ if (runNext) {
206
+ return next();
207
+ }
208
+ res.json(deleted);
209
+ }
210
+ catch (e) {
211
+ next(QueryError.catch(e));
212
+ }
213
+ };
214
+ }
215
+ bulkArchive({ runNext }) {
216
+ return async (req, res, next) => {
217
+ try {
218
+ const ids = this.validateIdsInBody(req);
219
+ this.init(req);
220
+ await this.handler.updateMany(this.query(req).root || {}, ids, {
221
+ [this.options.archiveKey]: true,
222
+ });
223
+ if (runNext) {
224
+ return next();
225
+ }
226
+ res.json(ids.map((_id) => ({ _id, [String(this.options.archiveKey)]: true })));
227
+ }
228
+ catch (e) {
229
+ next(QueryError.catch(e));
230
+ }
231
+ };
232
+ }
233
+ addToNextQuery(fn) {
234
+ return (req, _, next) => {
235
+ try {
236
+ const data = fn(req);
237
+ if (data) {
238
+ this.query(req).addRootNext(data);
239
+ }
240
+ next();
241
+ }
242
+ catch (e) {
243
+ next(QueryError.catch(e));
244
+ }
245
+ };
246
+ }
247
+ subRoute(req, _res, next) {
248
+ try {
249
+ this.validateReq(req);
250
+ this.init(req);
251
+ if (!req.ewb.queryPostBody) {
252
+ req.ewb.queryPostBody = {};
253
+ }
254
+ const doc = this.getDoc(req);
255
+ req.ewb.queryPostBody[this.param] = doc._id;
256
+ this.query(req).addRoot({
257
+ [this.param]: doc._id,
258
+ });
259
+ next();
260
+ }
261
+ catch (e) {
262
+ next(QueryError.catch(e));
263
+ }
264
+ }
265
+ subDoc(reqKey, subArrayKey) {
266
+ return new QueryExpressSub(this.handler, this, reqKey, subArrayKey);
267
+ }
268
+ addRootRequest(req) {
269
+ this.query(req).addRoot(this.getRootQuery(req));
270
+ }
271
+ getRootQuery(req) {
272
+ const param = this.getParam(req);
273
+ if (param.match(/^[0-9a-fA-F]{24}$/) &&
274
+ mongoose.Types.ObjectId.isValid(param)) {
275
+ return {
276
+ _id: new mongoose.Types.ObjectId(param),
277
+ };
278
+ }
279
+ if (this.options.slugKey) {
280
+ return { [this.options.slugKey]: param };
281
+ }
282
+ throw new QueryError(status.BAD_REQUEST, `Param is not valid`, {
283
+ detail: 'Need to be of type MongoDB ObjectID',
284
+ });
285
+ }
286
+ removeRootRequest(req, slugKey) {
287
+ this.query(req).deleteKeysFromRoot(['_id', ...(slugKey ? [slugKey] : [])]);
288
+ }
289
+ addToQuery(req, _res, next) {
290
+ try {
291
+ this.query(req).addRoot({
292
+ [this.param]: this.getDoc(req)._id,
293
+ });
294
+ next();
295
+ }
296
+ catch (e) {
297
+ next(QueryError.catch(e));
298
+ }
299
+ }
300
+ addToPost(req, _res, next) {
301
+ try {
302
+ this.validateReq(req);
303
+ if (!req.ewb.queryPostBody) {
304
+ req.ewb.queryPostBody = {};
305
+ }
306
+ req.ewb.queryPostBody[this.param] = this.getDoc(req)._id;
307
+ next();
308
+ }
309
+ catch (e) {
310
+ next(QueryError.catch(e));
311
+ }
312
+ }
313
+ getParam(req, param = this.param) {
314
+ if (req[param]) {
315
+ return this.getDoc(req, param)._id.toHexString();
316
+ }
317
+ if (!req.params[param]) {
318
+ throw new QueryError(status.BAD_REQUEST, String(param), {
319
+ detail: 'Param is not valid',
320
+ });
321
+ }
322
+ return req.params[param];
323
+ }
324
+ preHistory(req) {
325
+ if (this.options.history?.active && req.ewb.queryHistory) {
326
+ if (this.options.history.ignoreFields) {
327
+ req.ewb.queryHistory.setIgnoreFields(this.options.history.ignoreFields);
328
+ }
329
+ req.ewb.queryHistory.setModel(this.handler.model);
330
+ let doc = this.getDoc(req);
331
+ if (doc) {
332
+ if ('toObject' in doc) {
333
+ doc = doc.toObject();
334
+ }
335
+ req.ewb.queryHistory.setOldDoc(doc);
336
+ }
337
+ }
338
+ }
339
+ async postHistory(req, fetchNew) {
340
+ if (this.options.history?.active && req.ewb.queryHistory) {
341
+ let doc = this.getDoc(req);
342
+ if (fetchNew) {
343
+ doc = await req.ewb.queryHistory.findUpdated();
344
+ }
345
+ req.ewb.queryHistory.setUpdatedDoc(doc);
346
+ req.ewb.queryHistory.setDiff(doc._id).then();
347
+ }
348
+ }
349
+ init(req) {
350
+ this.query(req).model = this.param;
351
+ }
352
+ query(req) {
353
+ if (this.options.queryKey in req) {
354
+ return req[this.options.queryKey];
355
+ }
356
+ if (!req.ewb.query) {
357
+ throw new QueryError(status.INTERNAL_SERVER_ERROR, 'Query not init', {
358
+ detail: `ewb.query missing or queryKey option missing in QueryExpress ${String(this.param)}`,
359
+ });
360
+ }
361
+ return req.ewb.query;
362
+ }
363
+ pageLinkHeader(req, data) {
364
+ const rootUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
365
+ return getPageLinkHeader(rootUrl, this.query(req), data);
366
+ }
367
+ getDoc(req, param = this.param) {
368
+ return req[param];
369
+ }
370
+ getFindOpts(_req) {
371
+ return {
372
+ select: false,
373
+ populate: false,
374
+ };
375
+ }
376
+ validateReq(req) {
377
+ if (!req[this.param]) {
378
+ throw new QueryError(status.NOT_FOUND, String(this.param), {
379
+ detail: 'Param is not valid',
380
+ });
381
+ }
382
+ }
383
+ validateIdsInBody(req) {
384
+ if (!req.body.ids) {
385
+ throw new QueryError(status.BAD_REQUEST, 'ids', {
386
+ detail: 'ids is required',
387
+ });
388
+ }
389
+ return req.body.ids.map((x) => new mongoose.Types.ObjectId(x));
390
+ }
391
+ skipHandlerAction(req, action) {
392
+ if (req.ewb.queryOptions.skipHandlerAction === action) {
393
+ req.ewb.queryOptions.skipHandlerAction = undefined;
394
+ return true;
395
+ }
396
+ return false;
397
+ }
398
+ }
@@ -0,0 +1,22 @@
1
+ import { QueryModel } from '@ewb/mongoose-query';
2
+ import { NextFunction, Request, Response } from 'express';
3
+ import mongoose from 'mongoose';
4
+ import { QueryExpress } from './QueryExpress.js';
5
+ export declare class QueryExpressSub<R extends Request, DocType extends object, K extends keyof DocType, T extends mongoose.HydratedDocument<DocType, {
6
+ _id: mongoose.Types.ObjectId;
7
+ }>> {
8
+ private handler;
9
+ private express;
10
+ private param;
11
+ private subKey;
12
+ constructor(handler: QueryModel<DocType>, express: QueryExpress<R, DocType, T>, param: keyof R, subKey: K);
13
+ post(req: R, _res: Response, next: NextFunction): Promise<void>;
14
+ search(req: R, res: Response, next: NextFunction): Promise<Response<any, Record<string, any>>>;
15
+ findOne(req: R, _res: Response, next: NextFunction): Promise<void>;
16
+ patch(req: R, _res: Response, next: NextFunction): Promise<void>;
17
+ delete(req: R, _res: Response, next: NextFunction): Promise<void>;
18
+ json(req: R, res: Response, next: NextFunction): Promise<void>;
19
+ private getQuery;
20
+ private validateReq;
21
+ private getSubDoc;
22
+ }
@@ -0,0 +1,109 @@
1
+ import { QueryError } from '@ewb/mongoose-query';
2
+ import status from 'http-status';
3
+ import mongoose from 'mongoose';
4
+ export class QueryExpressSub {
5
+ constructor(handler, express, param, subKey) {
6
+ this.handler = handler;
7
+ this.express = express;
8
+ this.param = param;
9
+ this.subKey = subKey;
10
+ this.post = this.post.bind(this);
11
+ this.search = this.search.bind(this);
12
+ this.findOne = this.findOne.bind(this);
13
+ this.patch = this.patch.bind(this);
14
+ this.delete = this.delete.bind(this);
15
+ this.json = this.json.bind(this);
16
+ }
17
+ async post(req, _res, next) {
18
+ try {
19
+ this.express.addRootRequest(req);
20
+ req[this.param] = (await this.handler.subCreate(this.subKey, this.express.query(req), req.body));
21
+ this.validateReq(req);
22
+ this.express.postHistory(req, true).then();
23
+ this.express.removeRootRequest(req, this.express.options.slugKey);
24
+ await this.handler.subPopulate(this.express.query(req), this.getSubDoc(req), this.subKey, 'onPost');
25
+ next();
26
+ }
27
+ catch (e) {
28
+ next(QueryError.catch(e));
29
+ }
30
+ }
31
+ async search(req, res, next) {
32
+ try {
33
+ this.express.query(req).removeQuery('as');
34
+ const results = (await this.handler.subSearch(this.subKey, this.express.query(req), this.express.getRootQuery(req)));
35
+ res.setHeader('Link', this.express.pageLinkHeader(req, results));
36
+ res.setHeader('X-Total-Count', results.count);
37
+ if (req.query.as === 'array' || this.express.query(req).page > 0) {
38
+ return res.json(results.data);
39
+ }
40
+ res.json(results);
41
+ }
42
+ catch (e) {
43
+ next(QueryError.catch(e));
44
+ }
45
+ }
46
+ async findOne(req, _res, next) {
47
+ try {
48
+ this.express.addRootRequest(req);
49
+ req[this.param] = (await this.handler.subFindOne(this.subKey, this.express.query(req), this.getQuery(req)));
50
+ this.validateReq(req);
51
+ this.express.removeRootRequest(req, this.express.options.slugKey);
52
+ await this.handler.subPopulate(this.express.query(req), this.getSubDoc(req), this.subKey, 'onFindOne');
53
+ next();
54
+ }
55
+ catch (e) {
56
+ next(QueryError.catch(e));
57
+ }
58
+ }
59
+ async patch(req, _res, next) {
60
+ try {
61
+ this.express.addRootRequest(req);
62
+ req[this.param] = (await this.handler.subFindOneAndUpdate(this.subKey, this.express.query(req), this.getQuery(req), req.body));
63
+ this.validateReq(req);
64
+ this.express.postHistory(req, true).then();
65
+ this.express.removeRootRequest(req, this.express.options.slugKey);
66
+ await this.handler.subPopulate(this.express.query(req), this.getSubDoc(req), this.subKey, 'onPatch');
67
+ next();
68
+ }
69
+ catch (e) {
70
+ next(QueryError.catch(e));
71
+ }
72
+ }
73
+ async delete(req, _res, next) {
74
+ try {
75
+ this.express.addRootRequest(req);
76
+ req[this.param] = (await this.handler.subDelete(this.subKey, this.express.query(req), this.getQuery(req)));
77
+ this.express.postHistory(req, true).then();
78
+ this.validateReq(req);
79
+ this.express.removeRootRequest(req, this.express.options.slugKey);
80
+ next();
81
+ }
82
+ catch (e) {
83
+ next(QueryError.catch(e));
84
+ }
85
+ }
86
+ async json(req, res, next) {
87
+ try {
88
+ res.json(this.validateReq(req));
89
+ }
90
+ catch (e) {
91
+ next(QueryError.catch(e));
92
+ }
93
+ }
94
+ getQuery(req) {
95
+ const param = this.express.getParam(req, this.param);
96
+ return { _id: new mongoose.Types.ObjectId(param) };
97
+ }
98
+ validateReq(req) {
99
+ if (!req[this.param]) {
100
+ throw new QueryError(status.NOT_FOUND, 'Document not found', {
101
+ detail: `Param ${String(this.param)} not found`,
102
+ });
103
+ }
104
+ return req[this.param];
105
+ }
106
+ getSubDoc(req) {
107
+ return req[this.param];
108
+ }
109
+ }
@@ -0,0 +1,8 @@
1
+ import type { QueryExpressType } from './types.js';
2
+ declare global {
3
+ namespace Express {
4
+ interface Request {
5
+ ewb: QueryExpressType<any, any>;
6
+ }
7
+ }
8
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,8 @@
1
+ import './declarations.js';
2
+ import { NextFunction, Request, Response } from 'express';
3
+ export * from '@ewb/mongoose-query';
4
+ export * from './QueryExpress.js';
5
+ export * from './types.js';
6
+ import { QueryExpress } from './QueryExpress.js';
7
+ export declare function initQueryExpress(req: Request, _res: Response, next: NextFunction): void;
8
+ export default QueryExpress;
@@ -0,0 +1,15 @@
1
+ import './declarations.js';
2
+ import { Query } from '@ewb/mongoose-query';
3
+ export * from '@ewb/mongoose-query';
4
+ export * from './QueryExpress.js';
5
+ export * from './types.js';
6
+ import { QueryExpress } from './QueryExpress.js';
7
+ export function initQueryExpress(req, _res, next) {
8
+ req.ewb = {
9
+ ...req.ewb,
10
+ query: new Query(req.query),
11
+ queryOptions: {},
12
+ };
13
+ next();
14
+ }
15
+ export default QueryExpress;
@@ -0,0 +1,13 @@
1
+ import type { ISearchPaginate, Query, QueryHistory } from '@ewb/mongoose-query';
2
+ import mongoose from 'mongoose';
3
+ import type { IQueryExpressOptions } from './QueryExpress.js';
4
+ export interface QueryExpressType<R extends Request, T extends object> {
5
+ query: Query<R, T>;
6
+ queryHistory?: QueryHistory<any>;
7
+ queryOptions: IQueryExpressOptions;
8
+ queryPostBody?: {
9
+ [key: string]: string | mongoose.Types.ObjectId;
10
+ };
11
+ queryExportJson?: any[];
12
+ querySearchJson?: ISearchPaginate<any>;
13
+ }
@@ -0,0 +1 @@
1
+ export {};
package/lib/types.d.ts CHANGED
@@ -1,29 +1,3 @@
1
- /// <reference types="mongoose/types/types.js" />
2
- /// <reference types="mongoose/types/aggregate.js" />
3
- /// <reference types="mongoose/types/callback.js" />
4
- /// <reference types="mongoose/types/collection.js" />
5
- /// <reference types="mongoose/types/connection.js" />
6
- /// <reference types="mongoose/types/cursor.js" />
7
- /// <reference types="mongoose/types/document.js" />
8
- /// <reference types="mongoose/types/error.js" />
9
- /// <reference types="mongoose/types/expressions.js" />
10
- /// <reference types="mongoose/types/helpers.js" />
11
- /// <reference types="mongoose/types/middlewares.js" />
12
- /// <reference types="mongoose/types/indexes.js" />
13
- /// <reference types="mongoose/types/models.js" />
14
- /// <reference types="mongoose/types/mongooseoptions.js" />
15
- /// <reference types="mongoose/types/pipelinestage.js" />
16
- /// <reference types="mongoose/types/populate.js" />
17
- /// <reference types="mongoose/types/query.js" />
18
- /// <reference types="mongoose/types/schemaoptions.js" />
19
- /// <reference types="mongoose/types/schematypes.js" />
20
- /// <reference types="mongoose/types/session.js" />
21
- /// <reference types="mongoose/types/types.js" />
22
- /// <reference types="mongoose/types/utility.js" />
23
- /// <reference types="mongoose/types/validation.js" />
24
- /// <reference types="mongoose/types/virtuals.js" />
25
- /// <reference types="mongoose/types/inferrawdoctype.js" />
26
- /// <reference types="mongoose/types/inferschematype.js" />
27
1
  import type { ISearchPaginate, Query, QueryHistory } from '@ewb/mongoose-query';
28
2
  import mongoose from 'mongoose';
29
3
  import type { IQueryExpressOptions } from './QueryExpress.js';
package/package.json CHANGED
@@ -1,36 +1,24 @@
1
1
  {
2
2
  "name": "@ewb/mongoose-query-express",
3
- "version": "1.1.2",
3
+ "version": "1.3.0",
4
4
  "type": "module",
5
5
  "description": "Routes and controllers for express to handle mongoose queries",
6
6
  "main": "./lib/index.js",
7
7
  "types": "./lib/index.d.ts",
8
- "scripts": {
9
- "dev": "yarn build:watch",
10
- "build": "tsc",
11
- "build:watch": "tsc --watch --incremental",
12
- "lint": "tslint --project \"./tsconfig.json\"",
13
- "test": "vitest run",
14
- "test:ui": "vitest --ui",
15
- "postversion": "git push && git push --tags",
16
- "prepublish": "yarn test && yarn build",
17
- "preversion": "yarn build"
18
- },
19
8
  "dependencies": {
20
- "http-status": "^1.6.2"
9
+ "http-status": "^2.1.0"
21
10
  },
22
11
  "devDependencies": {
23
12
  "@ewb/mongoose-query": "*",
24
- "@types/express": "^4.17.17",
25
- "@vitest/ui": "^0.31.1",
26
- "express": "^4.18.2",
27
- "husky": "^8.0.3",
28
- "lint-staged": "^13.2.2",
29
- "mongoose": "^8.4.1",
30
- "prettier": "^2.8.8",
31
- "tslint": "^6.1.3",
32
- "typescript": "^5.4.5",
33
- "vitest": "^0.31.1"
13
+ "@types/express": "^5.0.6",
14
+ "@types/node": "^24.19.2",
15
+ "@vitest/ui": "^5.1.0",
16
+ "express": "^5.3.0",
17
+ "mongoose": "^9.12.1",
18
+ "prettier": "^3.10.1",
19
+ "typescript": "^7.0.2",
20
+ "vite": "^8.3.8",
21
+ "vitest": "^5.1.0"
34
22
  },
35
23
  "peerDependencies": {
36
24
  "@ewb/mongoose-query": "*"
@@ -53,11 +41,16 @@
53
41
  "files": [
54
42
  "lib"
55
43
  ],
56
- "husky": {
57
- "hooks": {
58
- "pre-commit": "pretty-quick --staged"
59
- }
60
- },
61
44
  "resolutions": {},
62
- "packageManager": "yarn@1.22.19+sha1.4ba7fc5c6e704fce2066ecbfb0b0d8976fe62447"
63
- }
45
+ "scripts": {
46
+ "dev": "pnpm build:watch",
47
+ "build": "tsc",
48
+ "build:watch": "tsc --watch --incremental",
49
+ "lint": "tslint --project \"./tsconfig.json\"",
50
+ "test": "vitest run",
51
+ "test:ui": "vitest --ui",
52
+ "postversion": "git push && git push --tags",
53
+ "prepublish": "pnpm test && pnpm build",
54
+ "preversion": "pnpm build"
55
+ }
56
+ }