Skip to content

Commit

Permalink
refactor: Simplify accessing mongoose models
Browse files Browse the repository at this point in the history
Currently mongoose models are accessed via db connection and require a typecast.
```
import { UserModel } from './user.model';

const User = dbs.admin.model('User') as UserModel;
```

Since model registry is tied to the db connection, there is no need to access it in this way.  We can just import the model directly since it is already being exported.

```
import { User } from './user.model';
```

For use cases where multiple db connections are used.  Models should explicitly be registered on the appropriate connection.
```
// Register model on default/admin db connection
export const MyModel = model('MyModel', MyModelSchema);

// Register model on secondary db connection
export const OtherModel = dbs.other.model('OtherModel', OtherModelSchema);
```
  • Loading branch information
jrassa committed Aug 16, 2023
1 parent 5ec0bf4 commit 61b289e
Show file tree
Hide file tree
Showing 41 changed files with 239 additions and 270 deletions.
6 changes: 2 additions & 4 deletions src/app/core/access-checker/access-checker.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@ import should from 'should';
import { createSandbox } from 'sinon';

import accessChecker from './access-checker.service';
import { CacheEntryModel, ICacheEntry } from './cache/cache-entry.model';
import { CacheEntry, ICacheEntry } from './cache/cache-entry.model';
import cacheEntryService from './cache/cache-entry.service';
import { config, dbs } from '../../../dependencies';

const CacheEntry = dbs.admin.model('CacheEntry') as CacheEntryModel;
import { config } from '../../../dependencies';

/**
* Helpers
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import should from 'should';

import { CacheEntryModel } from './cache-entry.model';
import { CacheEntry } from './cache-entry.model';
import cacheEntryService from './cache-entry.service';
import { dbs } from '../../../../dependencies';

const CacheEntry = dbs.admin.model('CacheEntry') as CacheEntryModel;

/**
* Unit tests
Expand Down
16 changes: 8 additions & 8 deletions src/app/core/access-checker/cache/cache-entry.service.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { FilterQuery } from 'mongoose';

import { CacheEntryDocument, CacheEntryModel } from './cache-entry.model';
import { dbs, utilService } from '../../../../dependencies';
import {
CacheEntry,
CacheEntryDocument,
CacheEntryModel
} from './cache-entry.model';
import { utilService } from '../../../../dependencies';
import { PagingResults } from '../../../common/mongoose/paginate.plugin';

class CacheEntryService {
model: CacheEntryModel;

constructor() {
this.model = dbs.admin.model('CacheEntry') as CacheEntryModel;
}
constructor(private model: CacheEntryModel) {}

/**
* Get the entry from the cache. Gets the most recent version.
Expand Down Expand Up @@ -68,4 +68,4 @@ class CacheEntryService {
}
}

export = new CacheEntryService();
export = new CacheEntryService(CacheEntry);
6 changes: 2 additions & 4 deletions src/app/core/access-checker/cache/cache-refresh.job.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { Job } from 'agenda';

import { CacheEntryModel } from './cache-entry.model';
import { dbs, logger } from '../../../../dependencies';
import { CacheEntry } from './cache-entry.model';
import { logger } from '../../../../dependencies';
import { JobService } from '../../../common/agenda/job-service';
import accessChecker from '../access-checker.service';

const CacheEntry = dbs.admin.model('CacheEntry') as CacheEntryModel;

export default class CacheRefreshJobService implements JobService {
async run(job: Job) {
const refresh = job.attrs.data.refresh ?? 8 * 3600000; // default to 8 hours;
Expand Down
6 changes: 2 additions & 4 deletions src/app/core/audit/audit.controller.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import _ from 'lodash';

import { AuditModel } from './audit.model';
import { dbs, utilService as util } from '../../../dependencies';

const Audit = dbs.admin.model('Audit') as AuditModel;
import { Audit } from './audit.model';
import { utilService as util } from '../../../dependencies';

/**
* Retrieves the distinct values for a field in the Audit collection
Expand Down
5 changes: 1 addition & 4 deletions src/app/core/audit/audit.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import should from 'should';

import { AuditModel } from './audit.model';
import { Audit } from './audit.model';
import auditService from './audit.service';
import { dbs } from '../../../dependencies';
import { IUser } from '../user/user.model';

const Audit = dbs.admin.model('Audit') as AuditModel;

/**
* Globals
*/
Expand Down
8 changes: 2 additions & 6 deletions src/app/core/audit/audit.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Request } from 'express';

import { AuditDocument, AuditModel } from './audit.model';
import { Audit, AuditDocument } from './audit.model';
import {
dbs,
config,
logger,
auditLogger,
Expand Down Expand Up @@ -34,17 +33,14 @@ class AuditService {
eventObject: unknown,
eventMetadata = null
): Promise<AuditDocument> {
// Delay resolving the Audit model until we can be sure it has been initialized
const Audit = dbs.admin.model('Audit') as AuditModel;

requestOrEventActor = await requestOrEventActor;

let actor = {};
if (this.isUser(requestOrEventActor)) {
actor = requestOrEventActor;
} else if (requestOrEventActor.user && requestOrEventActor.headers) {
const user = requestOrEventActor.user as UserDocument;
actor = await user.auditCopy(
actor = user.auditCopy(
utilService.getHeaderField(requestOrEventActor.headers, 'x-real-ip')
);
eventMetadata = requestOrEventActor.headers;
Expand Down
2 changes: 1 addition & 1 deletion src/app/core/export/export-config.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ ExportConfigSchema.methods.auditCopy = function () {
/**
* Model Registration
*/
export const Message = model<IExportConfig, ExportConfigModel>(
export const ExportConfig = model<IExportConfig, ExportConfigModel>(
'ExportConfig',
ExportConfigSchema
);
11 changes: 7 additions & 4 deletions src/app/core/export/export-config.service.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { Types } from 'mongoose';

import { ExportConfigDocument, ExportConfigModel } from './export-config.model';
import { dbs } from '../../../dependencies';
import {
ExportConfig,
ExportConfigDocument,
ExportConfigModel
} from './export-config.model';

class ExportConfigService {
model = dbs.admin.model('ExportConfig') as ExportConfigModel;
constructor(private model: ExportConfigModel) {}

/**
* Generate a new ExportConfig document in the collection.
Expand All @@ -22,4 +25,4 @@ class ExportConfigService {
}
}

export = new ExportConfigService();
export = new ExportConfigService(ExportConfig);
9 changes: 3 additions & 6 deletions src/app/core/feedback/feedback.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import { assert, createSandbox, spy, stub } from 'sinon';

import * as feedbackController from './feedback.controller';
import { FeedbackModel } from './feedback.model';
import { Feedback } from './feedback.model';
import feedbackService from './feedback.service';
import { auditService, dbs, logger } from '../../../dependencies';
import { UserModel } from '../user/user.model';

const Feedback = dbs.admin.model('Feedback') as FeedbackModel;
const User = dbs.admin.model('User') as UserModel;
import { auditService, logger } from '../../../dependencies';
import { User } from '../user/user.model';

describe('Feedback Controller2', () => {
let res;
Expand Down
25 changes: 13 additions & 12 deletions src/app/core/feedback/feedback.controller.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import { FeedbackModel } from './feedback.model';
import feedbackService from './feedback.service';
import { auditService, config, dbs, utilService } from '../../../dependencies';
import { auditService, config } from '../../../dependencies';
import * as exportConfigController from '../export/export-config.controller';
import exportConfigService from '../export/export-config.service';

const Feedback = dbs.admin.model('Feedback') as FeedbackModel;

export const submitFeedback = async function (req, res) {
const audit = await auditService.audit(
'Feedback submitted',
Expand Down Expand Up @@ -62,16 +59,16 @@ export const adminGetFeedbackCSV = async function (req, res) {

const query = result.config.q ? JSON.parse(result.config.q) : null;
const search = result.config.s;
const sort = utilService.getSortObj(result.config);

const feedbackCursor = Feedback.find(query)
.textSearch(search)
.sort(sort)
.populate({
const feedbackCursor = feedbackService.cursorSearch(
result.config,
search,
query,
{
path: 'creator',
select: ['username', 'organization', 'name', 'email']
})
.cursor();
}
);

exportConfigController.exportCSV(
req,
Expand All @@ -86,7 +83,11 @@ export const search = async (req, res) => {
const results = await feedbackService.search(
req.query,
req.body.s,
req.body.q
req.body.q,
{
path: 'creator',
select: ['username', 'organization', 'name', 'email']
}
);
res.status(200).json(results);
};
Expand Down
9 changes: 3 additions & 6 deletions src/app/core/feedback/feedback.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import should from 'should';
import { assert, createSandbox } from 'sinon';

import { FeedbackModel } from './feedback.model';
import { Feedback } from './feedback.model';
import feedbackService from './feedback.service';
import { auditService, emailService, config, dbs } from '../../../dependencies';
import { UserModel } from '../user/user.model';

const User = dbs.admin.model('User') as UserModel;
const Feedback = dbs.admin.model('Feedback') as FeedbackModel;
import { auditService, emailService, config } from '../../../dependencies';
import { User } from '../user/user.model';

/**
* Unit tests
Expand Down
50 changes: 37 additions & 13 deletions src/app/core/feedback/feedback.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { Readable } from 'stream';

Check failure on line 1 in src/app/core/feedback/feedback.service.ts

View workflow job for this annotation

GitHub Actions / build (16.x, 4.2)

Cannot find name 'T'.

Check failure on line 1 in src/app/core/feedback/feedback.service.ts

View workflow job for this annotation

GitHub Actions / build (18.x, 4)

Cannot find name 'T'.

Check failure on line 1 in src/app/core/feedback/feedback.service.ts

View workflow job for this annotation

GitHub Actions / build (18.x, 4.2)

Cannot find name 'T'.

import { FilterQuery, PopulateOptions, Types } from 'mongoose';

import { FeedbackDocument, FeedbackModel, Statuses } from './feedback.model';
import {
dbs,
Feedback,
FeedbackDocument,
FeedbackModel,
Statuses
} from './feedback.model';
import {
config,
emailService,
logger,
Expand All @@ -12,11 +18,7 @@ import { PagingResults } from '../../common/mongoose/paginate.plugin';
import { UserDocument } from '../user/user.model';

class FeedbackService {
model: FeedbackModel;

constructor() {
this.model = dbs.admin.model('Feedback') as FeedbackModel;
}
constructor(private model: FeedbackModel) {}

create(
user: UserDocument,
Expand Down Expand Up @@ -65,7 +67,12 @@ class FeedbackService {
search(
queryParams = {},
search = '',
query: FilterQuery<FeedbackDocument> = {}
query: FilterQuery<FeedbackDocument> = {},
populate:
| string
| string[]
| PopulateOptions
| Array<string | PopulateOptions> = []
): Promise<PagingResults<FeedbackDocument>> {
const page = utilService.getPage(queryParams);
const limit = utilService.getLimit(queryParams, 100);
Expand All @@ -76,13 +83,30 @@ class FeedbackService {
.find(query)
.textSearch(search)
.sort(sort)
.populate({
path: 'creator',
select: ['username', 'organization', 'name', 'email']
})
.populate(populate as string[])
.paginate(limit, page);
}

cursorSearch(
queryParams = {},
search = '',
query: FilterQuery<T> = {},
populate:
| string
| string[]
| PopulateOptions
| Array<string | PopulateOptions> = []
): Readable {
const sort = utilService.getSortObj(queryParams);

return this.model
.find(query)
.textSearch(search)
.sort(sort)
.populate(populate as string[])
.cursor();
}

async sendFeedbackEmail(
user: UserDocument,
feedback: FeedbackDocument,
Expand Down Expand Up @@ -133,4 +157,4 @@ class FeedbackService {
}
}

export = new FeedbackService();
export = new FeedbackService(Feedback);
13 changes: 3 additions & 10 deletions src/app/core/messages/messages.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
import mongoose from 'mongoose';
import should from 'should';

import { DismissedMessageModel } from './dismissed-message.model';
import { MessageModel } from './message.model';
import { DismissedMessage } from './dismissed-message.model';
import { Message } from './message.model';
import messagesService from './messages.service';
import { dbs } from '../../../dependencies';
import { UserModel } from '../user/user.model';

const User = dbs.admin.model('User') as UserModel;
const Message = dbs.admin.model('Message') as MessageModel;
const DismissedMessage = dbs.admin.model(
'DismissedMessage'
) as DismissedMessageModel;
import { User } from '../user/user.model';

/**
* Helpers
Expand Down
24 changes: 13 additions & 11 deletions src/app/core/messages/messages.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,29 @@ import path from 'path';
import { FilterQuery, PopulateOptions, Types } from 'mongoose';

import {
DismissedMessage,
DismissedMessageDocument,
DismissedMessageModel,
IDismissedMessage
} from './dismissed-message.model';
import { IMessage, MessageDocument, MessageModel } from './message.model';
import { dbs, config, utilService } from '../../../dependencies';
import {
IMessage,
Message,
MessageDocument,
MessageModel
} from './message.model';
import { config, utilService } from '../../../dependencies';
import { PublishProvider } from '../../common/event/publish.provider';
import { PagingResults } from '../../common/mongoose/paginate.plugin';
import { UserDocument } from '../user/user.model';

class MessagesService {
model: MessageModel;
dismissedModel: DismissedMessageModel;
publishProvider: PublishProvider;

constructor() {
this.model = dbs.admin.model('Message') as MessageModel;
this.dismissedModel = dbs.admin.model(
'DismissedMessage'
) as DismissedMessageModel;
}
constructor(
private model: MessageModel,
private dismissedModel: DismissedMessageModel
) {}

create(user: UserDocument, doc: unknown): Promise<MessageDocument> {
const message = new this.model(doc);
Expand Down Expand Up @@ -144,4 +146,4 @@ class MessagesService {
}
}

export = new MessagesService();
export = new MessagesService(Message, DismissedMessage);
Loading

0 comments on commit 61b289e

Please sign in to comment.