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

feat(converter): Add createConverter function #9

Merged
merged 3 commits into from
Oct 5, 2018
Merged
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
103 changes: 102 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,108 @@ export declare class NullableRepository<Entity extends EntityLike<any>, Props ex
}
```

### Serializer
### Converter

> JSON <-> Props <-> Entity

Converter is that convert JSON <-> Props <-> Entity.

`createConverter` create interconversion function from `Props` and `JSON` types and mapping definition.

```ts
// Pass Props type and JSON types as generics
// 1st argument is that a Constructor of entity that is required for creating entity from JSON
// 2nd argument is that a mapping object
// mapping object has tuple array for each property.
// tuple is [Props to JSON, JSON to Props]
createConverter<PropsType, JSONType>(EntityConstructor, mappingObject)
```

mapping object has has tuple array for each property.

```ts
const converter = createConverter<EntityProps, EntityJSON>(Entity, {
id: [propsToJSON function, jsonToProps function],
// [(prop value) => json value, (json value) => prop value]
});
```

Example of `createConveter`.

```ts

// Entity A
class AIdentifier extends Identifier<string> {}

interface AEntityArgs {
id: AIdentifier;
a: number;
b: string;
}

class AEntity extends Entity<AIdentifier> {
private a: number;
private b: string;

constructor(args: AEntityArgs) {
super(args.id);
this.a = args.a;
this.b = args.b;
}

toJSON(): AEntityJSON {
return {
id: this.id.toValue(),
a: this.a,
b: this.b
};
}
}
// JSON
interface AEntityJSON {
id: string;
a: number;
b: string;
}
// Create converter
// Tuple has two convert function that Props -> JSON and JSON -> Props
const converter = createConverter<AProps, AEntityJSON>(AEntity, {
// conveter definition for each property.
id: [prop => prop.toValue(), json => new AIdentifier(json)],
a: [prop => prop, json => json],
b: [prop => prop, json => json]
});
const entity = new AEntity({
id: new AIdentifier("a"),
a: 42,
b: "b prop"
});
// Entity to JSON
const json = converter.entityToJSON(entity);
assert.deepStrictEqual(json, {
id: "a",
a: 42,
b: "b prop"
});
// JSON to Entity
const entity_conveterted = converter.jsonToEntity(json);
assert.deepStrictEqual(entity, entity_conveterted);
// JSON to Props
const props = converter.jsonToProps(json);
assert.deepStrictEqual(props, entity.props);
```

:memo: Limitation:

Convert can be possible one for one converting.

```
// Can not do convert following pattern
// JSON -> Entity
// a -> b, c properties
```

### [Deprecated] Serializer

> JSON <-> Entity

Expand Down
26 changes: 15 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@
"main": "lib/index.js",
"types": "lib/index.d.ts",
"scripts": {
"precommit": "lint-staged",
"postcommit": "git reset",
"prettier": "prettier --write '{src,test}/**/*.ts'",
"test": "mocha 'test/*.ts'",
"build": "cross-env NODE_ENV=production tsc -p .",
Expand Down Expand Up @@ -46,20 +44,26 @@
},
"homepage": "https://github.com/almin/ddd-base",
"devDependencies": {
"@types/mocha": "^5.2.0",
"@types/node": "^10.1.2",
"cross-env": "^5.1.5",
"husky": "^0.14.3",
"lerna": "^2.11.0",
"lint-staged": "^7.1.1",
"@types/mocha": "^5.2.5",
"@types/node": "^10.11.4",
"cross-env": "^5.2.0",
"husky": "^1.1.0",
"lerna": "^3.4.1",
"lint-staged": "^7.3.0",
"mocha": "^5.2.0",
"prettier": "1.12.1",
"prettier": "1.14.3",
"rimraf": "^2.6.2",
"ts-node": "^6.0.3",
"typescript": "^2.8.3"
"ts-node": "^7.0.1",
"typescript": "^3.1.1"
},
"dependencies": {
"map-like": "^2.0.0",
"shallow-equal-object": "^1.1.1"
},
"husky": {
"hooks": {
"post-commit": "git reset",
"pre-commit": "lint-staged"
}
}
}
61 changes: 61 additions & 0 deletions src/Converter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { Entity } from "./Entity";
import { EntityLikeProps } from "./EntityLike";
import { Identifier } from "./Identifier";
import { Constructor } from "./TypeUtil";

/**
* Create convert that convert JSON <-> Props <-> Entity.
* Limitation: Convert can be possible one for one converting.
* @param EntityConstructor
* @param mappingPropsAndJSON
*/
export const createConverter = <
EntityProps extends EntityLikeProps<Identifier<any>>,
EntityJSON extends { [P in keyof EntityProps]: any },
T extends Entity<EntityProps> = Entity<EntityProps>,
EntityConstructor extends Constructor<T> = Constructor<T>
>(
EntityConstructor: EntityConstructor,
mappingPropsAndJSON: {
[P in keyof EntityProps]: [(prop: EntityProps[P]) => EntityJSON[P], (json: EntityJSON[P]) => EntityProps[P]]
}
) => {
return {
/**
* Convert Entity to JSON format
*/
entityToJSON(entity: T): EntityJSON {
const json: any = {};
Object.keys(entity.props).forEach(key => {
json[key] = mappingPropsAndJSON[key][0](entity.props[key]);
});
return json;
},
/**
* Convert Entity to Props
*/
entityToProps(entity: T): EntityProps {
return entity.props;
},
/**
* Convert JSON to Props
*/
jsonToProps(json: EntityJSON): EntityProps {
const props: any = {};
Object.keys(json).forEach(key => {
props[key] = mappingPropsAndJSON[key][1]((json as any)[key]);
});
return props as EntityProps;
},
/**
* Convert JSON to Entity
*/
jsonToEntity(json: EntityJSON): T {
const props: any = {};
Object.keys(json).forEach(key => {
props[key] = mappingPropsAndJSON[key][1]((json as any)[key]);
});
return new EntityConstructor(props as EntityProps);
}
};
};
1 change: 1 addition & 0 deletions src/EntityLike.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Identifier } from "./Identifier";

export interface EntityLikeProps<Id extends Identifier<any>> {
id: Id;
[index: string]: any;
}

export interface EntityLike<Props extends EntityLikeProps<Identifier<any>>> {
Expand Down
4 changes: 4 additions & 0 deletions src/TypeUtil.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/**
* Constructor type
*/
export type Constructor<T = {}> = new (...args: any[]) => T;
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ export {
RepositoryEvents
} from "./repository/RepositoryEventEmitter";

export { createConverter } from "./Converter";
// @deprecated
// Use `createConverter` instead of it
export { Serializer } from "./Serializer";
// status: Experimental
// mixin
Expand Down
6 changes: 1 addition & 5 deletions src/mixin/Copyable.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import { Identifier } from "../Identifier";
import { EntityLikeProps } from "../EntityLike";
import { EntityLike } from "../EntityLike";

/**
* Constructor type
*/
export type Constructor<T = {}> = new (...args: any[]) => T;
import { Constructor } from "../TypeUtil";

/**
*
Expand Down
74 changes: 74 additions & 0 deletions test/Conveter-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import assert = require("assert");
import { Entity, Identifier, createConverter } from "../src";

// Entity A
class AIdentifier extends Identifier<string> {}

interface AProps {
id: AIdentifier;
a: number;
b: string;
}

class AEntity extends Entity<AProps> {
constructor(args: AProps) {
super(args);
}

toJSON(): AEntityJSON {
return {
id: this.props.id.toValue(),
a: this.props.a,
b: this.props.b
};
}
}

interface AEntityJSON {
id: string;
a: number;
b: string;
}

describe("Converter", function() {
it("should convert JSON <-> Entity", () => {
const converter = createConverter<AProps, AEntityJSON>(AEntity, {
id: [prop => prop.toValue(), json => new AIdentifier(json)],
a: [prop => prop, json => json],
b: [prop => prop, json => json]
});
const entity = new AEntity({
id: new AIdentifier("a"),
a: 42,
b: "b prop"
});
const json = converter.entityToJSON(entity);
assert.deepStrictEqual(json, {
id: "a",
a: 42,
b: "b prop"
});
const entity2 = converter.jsonToEntity(json);
assert.deepStrictEqual(entity, entity2);
});
it("should convert Props <-> Entity", () => {
const converter = createConverter<AProps, AEntityJSON>(AEntity, {
id: [prop => prop.toValue(), json => new AIdentifier(json)],
a: [prop => prop, json => json],
b: [prop => prop, json => json]
});
const entity = new AEntity({
id: new AIdentifier("a"),
a: 42,
b: "b prop"
});
const json = converter.entityToJSON(entity);
assert.deepStrictEqual(json, {
id: "a",
a: 42,
b: "b prop"
});
const props = converter.jsonToProps(json);
assert.deepStrictEqual(props, entity.props);
});
});
4 changes: 2 additions & 2 deletions test/Serializer-test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Identifier, Serializer } from "../src";
import { Entity } from "../src";
import * as assert from "assert";
import { Identifier, Serializer, Entity } from "../src";

describe("Serializer", () => {
// Entity A
Expand Down Expand Up @@ -51,6 +50,7 @@ describe("Serializer", () => {
a: 42,
b: "b prop"
});

const json = ASerializer.toJSON(entity);
assert.deepStrictEqual(json, {
id: "a",
Expand Down
Loading