Skip to content
This repository has been archived by the owner on Aug 16, 2024. It is now read-only.

Commit

Permalink
update: FXD-13108 调整 manager 封装 & 补充测试用例
Browse files Browse the repository at this point in the history
  • Loading branch information
huhamhire committed Dec 1, 2020
1 parent 4ed61c1 commit e2eccab
Show file tree
Hide file tree
Showing 9 changed files with 133 additions and 28 deletions.
1 change: 0 additions & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,3 @@ coverage/

.vscode/
.idea/

21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 nstarter

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.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
{
"name": "nstarter-entity",
"version": "0.1.0",
"license": "MIT",
"scripts": {
"compile": "tsc --build tsconfig.json",
"build": "rimraf dist && npm run compile",
"lint": "eslint --config .eslintrc.js --ext .ts --quiet ./src",
"test": "nyc mocha --config .mocharc.yml --unhandled-rejections=none",
"schema": "typescript-json-schema ./test/entities/*.ts * --out ./resources/schema.entities.json --required --excludePrivate --ignoreErrors --noExtraProps"
},
"main": "./dist",
"types": "./dist",
"dependencies": {
"ajv": "^6.12.6"
},
Expand Down
6 changes: 3 additions & 3 deletions src/abstract.entity.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { schemaManager } from './schema.manager';
import { SchemaManager } from './schema.manager';
import { Definition } from 'typescript-json-schema';
import { ValidateFunction } from 'ajv';
import { ValidationError } from './error';
Expand All @@ -18,8 +18,8 @@ export abstract class AbstractEntity {
constructor(obj?: any) {
// 加载 schema
const name = this.constructor.name;
this._schema = schemaManager.getSchema(name);
this._validator = schemaManager.getValidator(name);
this._schema = SchemaManager.getInstance().getSchema(name);
this._validator = SchemaManager.getInstance().getValidator(name);

// 初始化
if (obj) {
Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export { ISchemaFormats, ISchemaManagerConfig } from './types';
export { ISchemaFormats } from './types';
export { AbstractEntity } from './abstract.entity';
export {} from './schema.manager';
export { SchemaManager } from './schema.manager';
60 changes: 44 additions & 16 deletions src/schema.manager.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,83 @@
import * as fs from 'fs';
import Ajv, { ValidateFunction } from 'ajv';
import { Definition } from 'typescript-json-schema';
import { ISchemaFormats, ISchemaManagerConfig } from './types';
import { ISchemaFormats } from './types';

/**
* 实例模型管理器
*/
class EntitySchemaManager {
export class SchemaManager {
private static instance: SchemaManager;

private readonly _ajv: Ajv.Ajv;
private readonly _schemaValidatorMap: {
[key: string]: Ajv.ValidateFunction
} = {};
private readonly _schemaDefinitionMap: {
[key: string]: Definition
} = {};
private readonly _schemaCustomTypes: ISchemaFormats = {};

/**
* @constructor
* @param config - 配置
* @param definition - 配置
*/
constructor(config: ISchemaManagerConfig) {
constructor(definition: string) {
// 加载结构定义
try {
const content = JSON.parse(
fs.readFileSync(config.definitions, {
fs.readFileSync(definition, {
encoding: 'utf-8'
})
);
this._schemaDefinitionMap = content.definitions || {};
} catch (err) {
throw new Error(`Failed to load schema definition file "${ config.definitions }".`);
throw new Error(`Failed to load schema definition file "${ definition }".`);
}

// 初始化 Ajv 实例
this._schemaCustomTypes = config.formats || {};
this._ajv = new Ajv({
useDefaults: true,
coerceTypes: true,
removeAdditional: true,
$data: true
});
}

/**
* 初始化实例
* @param definition
* @constructor
*/
public static Initialize(definition: string) {
// 只能被初始化一次
if (SchemaManager.instance) {
throw new Error('EntitySchemaManager could only be initialized once.');
}
SchemaManager.instance = new SchemaManager(definition);
return SchemaManager.instance;
}


// 定义自定义格式
for (const format in this._schemaCustomTypes) {
if (this._schemaCustomTypes.hasOwnProperty(format)) {
const pattern = this._schemaCustomTypes[format];
/**
* 获取实例
* @returns {SchemaManager} - 获取实例
* @static
*/
public static getInstance() {
if (!SchemaManager.instance) {
throw new Error('EntitySchemaManager has not been initialized.');
}
return SchemaManager.instance;
}

/**
* 配置自定义数据格式
* @param formats
*/
public setSchemaFormats(formats: ISchemaFormats) {
for (const format in formats) {
if (formats.hasOwnProperty(format)) {
const pattern = formats[format];
this._ajv.addFormat(format, pattern);
}
}
Expand Down Expand Up @@ -75,7 +107,3 @@ class EntitySchemaManager {
return validator;
}
}

export const schemaManager = new EntitySchemaManager({
definitions: './resources/schema.entities.json'
});
5 changes: 0 additions & 5 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,3 @@ import { FormatValidator } from 'ajv';
export interface ISchemaFormats {
[format: string]: FormatValidator;
}

export interface ISchemaManagerConfig {
definitions: string;
formats?: ISchemaFormats;
}
5 changes: 5 additions & 0 deletions test/invalid/invalid.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { AbstractEntity } from '../../src';

export class InvalidEntity extends AbstractEntity {
invalid = true;
}
56 changes: 55 additions & 1 deletion test/test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,53 @@
import chai from 'chai';

import { TestEntity } from './entities/test.entity';
import { InvalidEntity } from './invalid/invalid.entity';
import { SchemaManager } from '../src';

const expect = chai.expect;

describe('SchemaManager', async() => {
it('getInstance without initialize', async () => {
try {
SchemaManager.getInstance()
} catch (err) {
// 未初始化加载实例
expect(err).to.exist;
}
});

it('Wrong definition', async() => {
try {
const schemaManager = SchemaManager.Initialize('./resources/schema.invalid.json');
schemaManager.setSchemaFormats({
'oid': /^[0-9a-f]{24}$/
});
} catch (err) {
expect(err).to.exist;
}
});

it('Initialize', async() => {
try {
const schemaManager = SchemaManager.Initialize('./resources/schema.entities.json');
schemaManager.setSchemaFormats({
'oid': /^[0-9a-f]{24}$/
});
} catch (err) {
expect(err).to.not.exist;
}
});

it('Duplicate initialize', async() => {
try {
SchemaManager.Initialize('')
} catch (err) {
// 重复初始化
expect(err).to.exist;
}
});
});

describe('Schema Validation', async () => {
it('Normal', async () => {
let result;
Expand Down Expand Up @@ -36,7 +80,7 @@ describe('Schema Validation', async () => {

it('Invalid parameters', async () => {
try {
const test = new TestEntity({
new TestEntity({
width: 1,
height: -2,
extra: 3
Expand Down Expand Up @@ -65,3 +109,13 @@ describe('Schema Validation', async () => {
});
});
});

describe('Invalid Entity', async () => {
it('Invalid', async () => {
try {
new InvalidEntity();
} catch (err) {
expect(err).to.exist;
}
});
});

0 comments on commit e2eccab

Please sign in to comment.