Skip to content

Commit

Permalink
style: format and lint all files
Browse files Browse the repository at this point in the history
  • Loading branch information
kiki-kanri committed Nov 18, 2024
1 parent 01dcce6 commit 4db725a
Show file tree
Hide file tree
Showing 27 changed files with 252 additions and 205 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: Test Suite
on:
push:
tags:
- "v*"
- 'v*'

workflow_dispatch:

Expand Down
6 changes: 3 additions & 3 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ For extending the model with instance methods, statics, or virtuals, please refe
1. Copy the `.env.example` file to `.env` and update the MONGODB_URI value.

2. To run the project in development mode:
```bash
pnpm run dev
```
```bash
pnpm run dev
```

Feel free to modify [./src/index.ts](./src/index.ts) to test different functionalities.
2 changes: 1 addition & 1 deletion examples/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"private": true,
"type": "module",
"private": true,
"scripts": {
"dev": "tsx watch --env-file=./.env ./src/index.ts"
},
Expand Down
27 changes: 15 additions & 12 deletions examples/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
/* eslint-disable no-console */

import { setCustomMongooseOptions } from '@kikiutils/mongoose/options';
import s from '@kikiutils/mongoose/schema-builders';
import { buildMongooseModel } from '@kikiutils/mongoose/utils';
import { Schema } from 'mongoose';
import type { ProjectionType, QueryOptions, Types } from 'mongoose';
import { env } from 'node:process';
import type { Except } from 'type-fest';

// Load global types
Expand All @@ -16,7 +19,7 @@ import type {} from '@kikiutils/mongoose/types/data';
* the actual project shouldn't have this line
* (unless you want to handle it the same way as the default).
*/
process.env.MONGODB_URI ||= 'mongodb://127.0.0.1:27017/kikiutils-mongoose-example?directConnection=true';
env.MONGODB_URI ||= 'mongodb://127.0.0.1:27017/kikiutils-mongoose-example?directConnection=true';

/**
* Set custom mongoose options.
Expand All @@ -27,7 +30,7 @@ process.env.MONGODB_URI ||= 'mongodb://127.0.0.1:27017/kikiutils-mongoose-exampl
* Please make sure to set it before using buildMongooseModel,
* as it will not affect models that have already been built before setting it.
*/
setCustomMongooseOptions('beforeModelBuild', (schema) => {
setCustomMongooseOptions('beforeModelBuild', (_schema) => {
// console.log('building model with schema: ', schema);
});

Expand Down Expand Up @@ -78,20 +81,20 @@ interface UserMethodsAndOverrides {

interface UserModel extends BaseMongoosePaginateModel<User, UserMethodsAndOverrides> {
// Model static methods
findByAccount(account: string, projection?: ProjectionType<User> | null, options?: QueryOptions<User> | null): MongooseFindOneReturnType<User, UserDocument, {}, UserMethodsAndOverrides>;
findByAccount: (account: string, projection?: ProjectionType<User> | null, options?: QueryOptions<User> | null) => MongooseFindOneReturnType<User, UserDocument, object, UserMethodsAndOverrides>;
}

type UserDocument = MongooseHydratedDocument<User, UserMethodsAndOverrides>;
export type UserDocument = MongooseHydratedDocument<User, UserMethodsAndOverrides>;

// Define schema
const userSchema = new Schema<User, UserModel, UserMethodsAndOverrides>({
account: s.string().maxlength(16).trim.unique.required,
// @ts-expect-error
// @ts-expect-error Ignore this error.
// Use setRoundAndToFixedSetter to round up on save and setToStringGetter to convert to string on get
balance: s.decimal128().setRoundAndToFixedSetter().setToStringGetter.required,
email: s.string().lowercase.trim.nonRequired,
enabled: s.boolean().default(false).required,
password: s.string().private.required
password: s.string().private.required,
});

// Set methods
Expand All @@ -113,7 +116,7 @@ const user = await UserModel.create({
account: Array.from({ length: 8 }, () => String.fromCharCode((Math.random() > 0.5 ? 97 : 65) + Math.floor(Math.random() * 26))).join(''),
balance: '1000.501',
email: '[email protected]',
password: 'test-password'
password: 'test-password',
});

console.log('created user: ', user);
Expand All @@ -129,7 +132,7 @@ console.log('verifying user password');
console.log('verified user password: ', user.verifyPassword('test-password'));

// Define user log data interface
interface UserLogData extends BaseMongooseModelData<true, false> {
export interface UserLogData extends BaseMongooseModelData<true, false> {
content: string;
type: number;
user: Partial<UserData>;
Expand All @@ -140,14 +143,14 @@ interface UserLog extends BaseMongooseDocType<Except<UserLogData, 'user'>, true,
user: Types.Decimal128;
}

type UserLogDocument = MongooseHydratedDocument<UserLog>;
type UserLogModel = BaseMongoosePaginateModel<UserLog>;
export type UserLogDocument = MongooseHydratedDocument<UserLog>;
export type UserLogModel = BaseMongoosePaginateModel<UserLog>;

// Define schema
const userLogSchema = new Schema<UserLog, UserLogModel>({
content: s.string().trim.required,
type: s.number().required,
user: s.ref('User').required
user: s.ref('User').required,
});

// Build model
Expand All @@ -158,7 +161,7 @@ console.log('creating user log');
const userLog = await UserLogModel.create({
content: 'test content',
type: 1,
user: user._id
user: user._id,
});

console.log('created user log: ', userLog);
Expand Down
4 changes: 2 additions & 2 deletions examples/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"extends": "@kikiutils/tsconfigs/esnext/es2022.json",
"compilerOptions": {
"outDir": "./dist",
"paths": {
"@/*": ["./src/*"]
}
},
"outDir": "./dist"
},
"include": ["./src"]
}
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/** @type {import('jest').Config} */
module.exports = {
testEnvironment: 'node',
transform: { '^.+\\.tsx?$': ['ts-jest', { tsconfig: 'tsconfig.jest.json' }] }
transform: { '^.+\\.tsx?$': ['ts-jest', { tsconfig: 'tsconfig.jest.json' }] },
};
72 changes: 36 additions & 36 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,38 +2,12 @@
"name": "@kikiutils/mongoose",
"version": "2.1.0",
"description": "A Mongoose plugin for enhanced JSON normalization and common schema creation, with built-in support for pagination and automatic Decimal128 conversion.",
"license": "MIT",
"author": "kiki-kanri",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/kiki-kanri/kikiutils-node-mongoose.git"
},
"scripts": {
"build": "ts-project-builder ./src/constants.ts ./src/options.ts ./src/schema-builders/index.ts ./src/utils.ts --clean --preserve-modules",
"bumplog": "changelogen --bump",
"release": "pnpm run build && pnpm run test && changelogen --push --release && sh ./build-and-publish.sh",
"test": "jest --coverage"
},
"dependencies": {
"decimal.js": "^10.4.3",
"lodash": "^4.17.21",
"mongoose": "^8.8.1",
"mongoose-aggregate-paginate-v2": "^1.1.2",
"mongoose-paginate-v2": "^1.8.5",
"type-fest": "^4.27.0"
},
"devDependencies": {
"@kikiutils/changelogen": "^0.7.0",
"@kikiutils/eslint-config": "^0.3.0",
"@kikiutils/tsconfigs": "^3.0.2",
"@types/jest": "^29.5.14",
"@types/lodash": "^4.17.13",
"@types/node": "^22.9.0",
"jest": "^29.7.0",
"ts-jest": "^29.2.5",
"ts-project-builder": "^3.3.2",
"tslib": "^2.8.1"
},
"keywords": [
"Decimal128",
"json",
Expand All @@ -44,30 +18,56 @@
"plugin",
"schema"
],
"engines": {
"node": ">=18.12.1"
},
"exports": {
"./*": {
"types": "./*.d.ts",
"import": "./*.mjs",
"require": "./*.cjs",
"types": "./*.d.ts"
"require": "./*.cjs"
},
"./_internals": {
"types": null,
"import": null,
"require": null,
"types": null
"require": null
},
"./schema-builders": {
"types": "./schema-builders/index.d.ts",
"import": "./schema-builders/index.mjs",
"require": "./schema-builders/index.cjs",
"types": "./schema-builders/index.d.ts"
"require": "./schema-builders/index.cjs"
},
"./types": {
"types": "./types/index.d.ts"
},
"./types/*": {
"types": "./types/*.d.ts"
}
},
"engines": {
"node": ">=18.12.1"
},
"scripts": {
"build": "ts-project-builder ./src/constants.ts ./src/options.ts ./src/schema-builders/index.ts ./src/utils.ts --clean --preserve-modules",
"bumplog": "changelogen --bump",
"release": "pnpm run build && pnpm run test && changelogen --push --release && sh ./build-and-publish.sh",
"test": "jest --coverage"
},
"dependencies": {
"decimal.js": "^10.4.3",
"lodash": "^4.17.21",
"mongoose": "^8.8.1",
"mongoose-aggregate-paginate-v2": "^1.1.2",
"mongoose-paginate-v2": "^1.8.5",
"type-fest": "^4.27.0"
},
"devDependencies": {
"@kikiutils/changelogen": "^0.7.0",
"@kikiutils/eslint-config": "^0.3.1",
"@kikiutils/tsconfigs": "^3.0.2",
"@types/jest": "^29.5.14",
"@types/lodash": "^4.17.13",
"@types/node": "^22.9.0",
"jest": "^29.7.0",
"ts-jest": "^29.2.5",
"ts-project-builder": "^3.3.2",
"tslib": "^2.8.1"
}
}
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions src/plugins/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const { get: lodashGet, set: lodashSet, unset: lodashUnset } = lodash;
*
* @param schema - The Mongoose schema to apply the plugin to.
*/
export const mongooseNormalizePlugin = <S extends Schema>(schema: S) => {
export function mongooseNormalizePlugin<S extends Schema>(schema: S) {
const toJSON = schema.get('toJSON');
const toJSONTransform = toJSON?.transform;
schema.set('toJSON', {
Expand All @@ -37,8 +37,8 @@ export const mongooseNormalizePlugin = <S extends Schema>(schema: S) => {
delete copiedRet.__v;
if (toJSONTransform && typeof toJSONTransform !== 'boolean') return toJSONTransform(doc, copiedRet, options);
return copiedRet;
}
},
});
};
}

export default mongooseNormalizePlugin;
34 changes: 20 additions & 14 deletions src/schema-builders/base.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,34 @@
import type { Schema } from 'mongoose';

export const createBaseSchemaBuilderFactory = <Builder = Readonly<Record<string, any>>>(type: BooleanConstructor | DateConstructor | NumberConstructor | Schema.Types.ObjectId['constructor'] | StringConstructor) => {
const isFunctionKeys = new Set([
'default',
'enum',
'index',
'max',
'maxlength',
'min',
'minlength',
]);

export function createBaseSchemaBuilderFactory<Builder = Readonly<Record<string, any>>>(type: BooleanConstructor | DateConstructor | NumberConstructor | Schema.Types.ObjectId['constructor'] | StringConstructor) {
return (schema: Record<string, any> = {}) => {
schema.type = type;
return new Proxy(Object.freeze({}), {
get(_, key, receiver) {
if (typeof key === 'symbol') throw new Error('Cannot use symbol as a schema attribute');
if (key in schema) throw new Error(`Duplicate schema attribute: ${key}`);
if (isFunctionKeys.has(key)) return (value: any) => ((schema[key] = value), receiver);
if (isFunctionKeys.has(key)) {
return (value: any) => {
schema[key] = value;
return receiver;
};
}

if (key === 'nonRequired') return { ...schema };
if (key === 'required') return { ...schema, required: true };
schema[key] = true;
return receiver;
}
},
}) as Builder;
};
};

const isFunctionKeys = new Set([
'default',
'enum',
'index',
'max',
'maxlength',
'min',
'minlength'
]);
}
9 changes: 6 additions & 3 deletions src/schema-builders/boolean.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ import type { Merge } from 'type-fest';

import { createBaseSchemaBuilderFactory } from './base';

type BaseProps = { type: BooleanSchemaDefinition };
export type ExtendBooleanSchemaBuilder<Props extends BaseProps, ExtraOmitFields extends string> = Omit<BooleanSchemaBuilder<Props, ExtraOmitFields>, ExtraOmitFields | keyof Props>;
export type ExtendBooleanSchemaBuilder<Props extends BaseBooleanSchemaProps, ExtraOmitFields extends string> = Omit<BooleanSchemaBuilder<Props, ExtraOmitFields>, ExtraOmitFields | keyof Props>;

export interface BooleanSchemaBuilder<Props extends BaseProps = BaseProps, ExtraOmitFields extends string = never> {
export interface BaseBooleanSchemaProps {
type: BooleanSchemaDefinition;
}

export interface BooleanSchemaBuilder<Props extends BaseBooleanSchemaProps = BaseBooleanSchemaProps, ExtraOmitFields extends string = never> {
default: <T extends DefaultType<D> | ((this: any, doc: any) => DefaultType<D>) | null, D extends boolean>(value: T) => ExtendBooleanSchemaBuilder<Merge<Props, { default: T }>, ExtraOmitFields>;
index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendBooleanSchemaBuilder<Merge<Props, { index: T }>, ExtraOmitFields>;
nonRequired: Props;
Expand Down
Loading

0 comments on commit 4db725a

Please sign in to comment.