Skip to content

Commit

Permalink
feat: the first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Barrior committed Sep 20, 2019
0 parents commit 96b6bf3
Show file tree
Hide file tree
Showing 22 changed files with 5,602 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
20 changes: 20 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
.DS_Store
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln

# Test related
coverage
.nyc_output
.coveralls.yml

/dist/
2 changes: 2 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*
!/dist/*
7 changes: 7 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"printWidth": 80,
"tabWidth": 2,
"semi": false,
"singleQuote": true,
"trailingComma": "es5"
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2019-present Barrior <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
11 changes: 11 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: '<rootDir>/test/@helpers/jest-env.js',
roots: ['<rootDir>/src/', '<rootDir>/test/'],
testMatch: ['<rootDir>/test/**/*.ts'],
testPathIgnorePatterns: ['<rootDir>/test/@.+/'],
coveragePathIgnorePatterns: ['<rootDir>/test/@.+/'],
moduleNameMapper: {
'~/(.*)': '<rootDir>/src/$1',
},
}
54 changes: 54 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"name": "mongoose-modified-at",
"description": "Mongoose plugin that tracking the fields you specified and automatically record the time of their changes to DB.",
"version": "2.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"test": "jest --verbose",
"test:watch": "yarn test --watch",
"coverage": "jest --coverage --maxWorkers 4",
"build": "rm -rf dist/ && tsc -p tsconfig.build.json",
"lint": "tslint --fix"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.js": [
"npm run lint",
"git add"
]
},
"dependencies": {
"lodash": "^4.17.15"
},
"devDependencies": {
"@types/bluebird": "^3.5.27",
"@types/chance": "^1.0.6",
"@types/jest": "^24.0.18",
"@types/lodash": "^4.14.137",
"@types/mongoose": "^5.5.13",
"bluebird": "^3.5.5",
"chance": "^1.1.0",
"husky": "^3.0.4",
"jest": "^24.9.0",
"lint-staged": "^9.2.4",
"moment": "^2.24.0",
"mongodb-memory-server": "^5.2.2",
"mongoose": "^5.6.10",
"prettier": "^1.18.2",
"ts-jest": "^24.0.2",
"tslint": "^5.19.0",
"tslint-config-prettier": "^1.18.0",
"tslint-plugin-prettier": "^2.0.1",
"typescript": "^3.5.3"
},
"author": "Barrior",
"license": "MIT",
"engines": {
"node": ">=10"
}
}
181 changes: 181 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import {
assign,
forEach,
get,
includes,
isArray,
isBoolean,
isFunction,
isPlainObject,
isString,
keys,
omit,
} from 'lodash'

export interface IOptions {
suffix?: string
select?: boolean
fields?: string[]
[key: string]: any
}

export interface IObjectAny {
[key: string]: any
}

function handleOptions(options: string[] | IOptions) {
let suffix: string = modifiedAt.suffix
let fields: string[] = []
let select: boolean = true
const customList: {
[key: string]: (doc: IObjectAny) => boolean | undefined | null
} = {}

if (isArray(options)) {
fields = options
} else if (isPlainObject(options)) {
if (isString(options.suffix)) {
suffix = options.suffix
}

if (isBoolean(options.select)) {
select = options.select
}

if (isArray(options.fields)) {
fields = options.fields
}

forEach(omit(options, ['suffix', 'select', 'fields']), (value, key) => {
if (isFunction(value)) {
customList[key] = value
}
})
} else {
throw Error('Missing options or type error of parameter "options"')
}

return { suffix, select, fields, customList }
}

function modifiedAt(schema: any, options: string[] | IOptions): void {
const { suffix, select, fields, customList } = handleOptions(options)

function addTimeFieldToSchema(pathname: string): void {
schema.add({
[pathname]: { type: Date, select },
})
}

// Add schema for every field
forEach(fields, field => {
addTimeFieldToSchema(field + suffix)
})

// tslint:disable-next-line:variable-name
forEach(customList, (_value, pathname) => {
addTimeFieldToSchema(pathname)
})

async function setTimestamps(params: {
that?: any
purelySet?: boolean
doc: any
modifiedPaths: string[]
}) {
const purelySet = params.hasOwnProperty('purelySet')
? params.purelySet
: true

const updatePaths: string[] = []
let updateTime: Date = new Date()

forEach(params.modifiedPaths, path => {
if (includes(fields, path)) {
updatePaths.push(path + suffix)
}
})

for (const pathname in customList) {
if (customList.hasOwnProperty(pathname)) {
const truly = await customList[pathname](params.doc)
if (truly) {
updateTime = new Date()
updatePaths.push(pathname)
}
}
}

forEach(updatePaths, pathname => {
if (purelySet) {
params.that.set(pathname, updateTime)
} else {
params.that[pathname] = updateTime
}
})
}

// for Document
// tslint:disable-next-line:variable-name
schema.pre('save', async function(this: any, _next: any, opts: any) {
if (get(opts, 'modifiedAt') === false) {
return
}
await setTimestamps({
that: this,
doc: this,
modifiedPaths: this.modifiedPaths(),
})
})

// for Query
const updateHooks = ['findOneAndUpdate', 'update', 'updateOne', 'updateMany']
schema.pre(updateHooks, async function(this: any) {
const opts = this.getOptions()
if (opts.modifiedAt === false) {
return
}
const updates = this.getUpdate()
await setTimestamps({
that: this,
doc: assign({}, this.getFilter(), updates),
modifiedPaths: keys(updates),
})
})

// for Query
const replaceHooks = ['findOneAndReplace', 'replaceOne']
schema.pre(replaceHooks, async function(this: any) {
const opts = this.getOptions()
if (opts.modifiedAt === true) {
const updates = JSON.parse(JSON.stringify(this.getUpdate()))
await setTimestamps({
that: updates,
doc: assign({}, this.getFilter(), updates),
modifiedPaths: keys(updates),
purelySet: false,
})
this.setUpdate(updates)
}
})

// for Model
// tslint:disable-next-line:variable-name only-arrow-functions
schema.pre('insertMany', async function(_next: any, docs: any[], opts: any) {
if (get(opts, 'modifiedAt') === false) {
return
}
for (const doc of docs) {
await setTimestamps({
that: doc,
doc,
modifiedPaths: keys(doc),
purelySet: false,
})
}
})
}

modifiedAt.suffix = '_modifiedAt'

export default modifiedAt
12 changes: 12 additions & 0 deletions test/@helpers/connect-db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import mongoose from 'mongoose'

beforeAll(async () => {
await mongoose.connect((global as any).mongoUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
})

afterAll(async () => {
await mongoose.disconnect()
})
17 changes: 17 additions & 0 deletions test/@helpers/jest-env.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const NodeEnvironment = require('jest-environment-node')
const { MongoMemoryServer } = require('mongodb-memory-server')

class CustomEnvironment extends NodeEnvironment {
async setup() {
await super.setup()
this.global.mongoServer = new MongoMemoryServer()
this.global.mongoUri = await this.global.mongoServer.getConnectionString()
}

async teardown() {
await this.global.mongoServer.stop()
await super.teardown()
}
}

module.exports = CustomEnvironment
34 changes: 34 additions & 0 deletions test/@helpers/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import Chance from 'chance'
import moment, { MomentInput } from 'moment'

const chance = new Chance()

export function randomName(prefix?: string): string {
const randomStr = chance.string({ length: 10, alpha: true })
return prefix ? `${prefix}_${randomStr}` : randomStr
}

export function createBulk() {
const firstDocName = randomName('createBulk')
const secondDocName = randomName('createBulk')
const content = [
{ name: firstDocName, age: 1, sex: 'male' },
{ name: secondDocName, age: 2, sex: 'male' },
]
return { content, firstDocName, secondDocName }
}

export function isDateTypeAndValueValid(
modifiedTime: any,
params: { startTime: MomentInput; endTime?: MomentInput }
): void {
expect(modifiedTime instanceof Date).toBe(true)

const modifiedTimeValue: number = moment(modifiedTime).valueOf()
const startTime: number = moment(params.startTime).valueOf()
const endTime: number = moment(params.endTime || new Date()).valueOf()

expect(startTime <= modifiedTimeValue && modifiedTimeValue <= endTime).toBe(
true
)
}
Loading

0 comments on commit 96b6bf3

Please sign in to comment.