Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/add custom fields #55

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ module.exports = {
project: ['./tsconfig.eslint.json'],
},
extends: [
'airbnb-base',
'airbnb-typescript/base',
'plugin:import/typescript',
'plugin:jest/all',
Expand All @@ -23,5 +24,16 @@ module.exports = {
'prettier/prettier': ['error', { 'singleQuote': true }],
'lines-between-class-members': 1,
'no-underscore-dangle': 0,
'import/extensions': [
'error',
'ignorePackages',
{
'js': 'never',
'jsx': 'never',
'ts': 'never',
'tsx': 'never'
}
],
'import/no-extraneous-dependencies': ['error']
}
}
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ lib/
coverage/
.project
.DS_Store
.idea/
58 changes: 39 additions & 19 deletions __fixtures__/Post.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
/* eslint-disable no-await-in-loop */
// @flow
/* eslint-disable no-param-reassign, func-names */

import mongoose, { Schema, Document, Model } from 'mongoose';
import mongoose, { Document as MongooseDocument, Model } from 'mongoose';
import DiffPlugin, { IDiffModel } from '../src/index';
import DB from './db';

DB.init();
DB.open();

export interface IPostDoc extends Document {
export interface IPostDoc extends MongooseDocument {
title: string;
subjects: Array<{ name: string }>;
createdAt: Date;
updatedAt: Date;
}

interface IPostModel extends Model<IPostDoc> {
diffModel(): IDiffModel;
createDifferentSubjects(findObj: string, count: number): Promise<void>;
}

export const PostSchema: Schema<IPostDoc, IPostModel> = new mongoose.Schema(
export const PostSchema = new mongoose.Schema<IPostDoc, IPostModel>(
{
title: {
type: String,
Expand Down Expand Up @@ -46,20 +46,40 @@ export const PostSchema: Schema<IPostDoc, IPostModel> = new mongoose.Schema(
);

// for test purposes
PostSchema.statics.createDifferentSubjects = async function (
this: IPostModel,
title: string,
count: number
): Promise<void> {
for (let i = 1; i <= count; i += 1) {
const post = await this.findOne({ title }).exec();
if (post) {
post.subjects.push({ name: `name_${i}` });
await post.save();
PostSchema.statics.createDifferentSubjects =
async function createDifferentSubjects(
this: IPostModel,
title: string,
count: number
): Promise<void> {
for (let i = 1; i <= count; i += 1) {
const post = await this.findOne({ title }).exec();
if (post) {
post.subjects.push({ name: `name_${i}` });
await post.save();
}
}
}
};

type CustomDiffFields = {
upperCasedTitle: string;
};

PostSchema.plugin(DiffPlugin<IPostDoc>());
// eslint-disable-next-line jest/require-hook
PostSchema.plugin(
DiffPlugin<IPostDoc, CustomDiffFields>({
schemaDefinition: {
upperCasedTitle: String,
},
values: {
upperCasedTitle: (doc: IPostDoc) => {
return 'sdcsdc';
},
},
})
);

export const Post = DB.data.model<IPostDoc, IPostModel>('Post', PostSchema);
export const Post = DB.connection.model<IPostDoc, IPostModel>(
'Post',
PostSchema
);
27 changes: 1 addition & 26 deletions __fixtures__/__mocks__/db.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,6 @@
/* eslint-disable no-param-reassign, jest/require-top-level-describe, jest/no-hooks */
/* eslint-disable no-param-reassign */

import * as m from 'mongodb-memory-server';

const DB = jest.requireActual('../db').default;

const mongod = new m.MongoMemoryServer({});

DB.autoIndexOnceInDev = (opts: any) => {
opts.config.autoIndex = false;
};
DB.consoleErr = () => {};
DB.consoleLog = () => {};

const actualInit = DB.init;
DB.init = async () => {
process.env.MONGO_CONNECTION_STRING = await mongod.getConnectionString();
return actualInit();
};

const actualClose = DB.close;
DB.close = async () => {
await actualClose();
mongod.stop();
};

module.exports = DB;

beforeAll(async () => DB.init());
beforeAll(async () => DB.open());
afterAll(async () => DB.close());
75 changes: 28 additions & 47 deletions __fixtures__/db.ts
Original file line number Diff line number Diff line change
@@ -1,69 +1,50 @@
/* eslint-disable no-console */

import mongoose, { Connection } from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';

mongoose.Promise = global.Promise;

type DBNames = 'data';

export default class DB {
static mongoose = mongoose;
static consoleErr = console.error;
static consoleLog = console.log;
static _connectionStr: string;
class DB {
mongod: MongoMemoryServer;

static data: Connection = mongoose.createConnection();
connection: Connection = mongoose.createConnection();

static init(connectionStr?: string) {
if (connectionStr) this._connectionStr = connectionStr;
return Promise.all([DB.openDB('data')]);
constructor(mongod: MongoMemoryServer) {
this.mongod = mongod;
}

static close() {
return Promise.all([DB.closeDB('data')]);
}

static openDB(name: DBNames = 'data'): Promise<Connection> {
async open(): Promise<Connection> {
return new Promise((resolve, reject) => {
const uri = process.env.MONGO_CONNECTION_STRING || this._connectionStr;
const opts: any = {};

opts.promiseLibrary = global.Promise;
opts.autoReconnect = true;
opts.reconnectTries = Number.MAX_VALUE;
opts.reconnectInterval = 1000;
opts.useNewUrlParser = true;
const uri = this.mongod.getUri();

const db: any = DB[name];

db.consoleErr = DB.consoleErr;
db.consoleLog = DB.consoleLog;
this.connection.once('open', () => {
console.log(`Successfully connected to ${uri}`);
resolve(this.connection);
});

db.on('error', (e: any) => {
this.connection.on('error', (e: any) => {
if (e.message.code === 'ETIMEDOUT') {
db.consoleErr(Date.now(), e);
db.connect(uri, opts);
this.connection.openUri(uri, {});
}
db.consoleErr(e);
console.error(Date.now(), e);
});

db.once('open', () => {
db.consoleLog(`Successfully connected to ${uri}`);
resolve(db);
});
db.once('disconnected', () => {
db.consoleLog(`Disconnected from ${uri}`);
this.connection.once('disconnected', () => {
console.log(`Disconnected from ${uri}`);
reject();
});

db.openUri(uri, opts);
this.connection.openUri(uri, {});
});
}

static closeDB(name: DBNames = 'data'): Promise<any> {
if (DB[name]) {
return DB[name].close();
}
return Promise.resolve();
close(): Promise<any> {
return this.connection.close();
}

static async build() {
const mongod = await MongoMemoryServer.create();
return new DB(mongod);
}
}

const db = await DB.build();
export default db;
42 changes: 28 additions & 14 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,26 @@
"homepage": "https://github.com/borodayev/mongoose-history-diff",
"license": "MIT",
"peerDependencies": {
"mongoose": "^5.12.5"
"mongoose": "^6.0.14"
},
"devDependencies": {
"@types/jest": "^26.0.22",
"@typescript-eslint/eslint-plugin": "^4.22.0",
"@jest/globals": "^27.4.2",
"@types/jest": "^27.0.3",
"@typescript-eslint/eslint-plugin": "^5.4.0",
"@typescript-eslint/parser": "^5.4.0",
"cz-conventional-changelog": "^3.3.0",
"eslint": "^7.25.0",
"eslint-config-airbnb-typescript": "^12.3.1",
"eslint": "^8.3.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-airbnb-typescript": "^16.0.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jest": "^24.3.5",
"eslint-plugin-prettier": "^3.4.0",
"jest": "26.6.3",
"mongodb-memory-server": "^6.9.6",
"eslint-plugin-jest": "^25.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "27.3.1",
"mongodb-memory-server": "^8.0.3",
"prettier": "^2.2.1",
"semantic-release": "^17.4.2",
"ts-jest": "^26.5.5",
"semantic-release": "^18.0.1",
"ts-jest": "^27.0.7",
"typescript": "^4.2.4"
},
"publishConfig": {
Expand All @@ -59,19 +62,30 @@
},
"jest": {
"testEnvironment": "node",
"extensionsToTreatAsEsm": [
".ts"
],
"transform": {
"^.+\\.ts$": "ts-jest"
},
"globals": {
"ts-jest": {
"tsconfig": "tsconfig.test.json",
"useESM": true
}
},
"moduleNameMapper": {
"^(\\.{1,2}/.*)\\.js$": "$1"
},
"roots": [
"<rootDir>/src"
]
},
"scripts": {
"build": "yarn tsc",
"watch": "jest --watch",
"coverage": "jest --coverage --maxWorkers 2",
"lint": "eslint --ext .ts ./src",
"test": "yarn coverage && yarn lint",
"jest": "node --no-warnings --experimental-vm-modules node_modules/jest/bin/jest.js",
"test": "yarn lint && yarn jest --maxWorkers 2",
"semantic-release": "semantic-release"
}
}
Loading