Skip to content

Commit 203478a

Browse files
authored
Merge pull request #150 from gregolsky/v4.0
unify object mapper usage, remove import cycle
2 parents fbb2368 + 3023cfe commit 203478a

32 files changed

+162
-123
lines changed

README.md

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -625,7 +625,7 @@ docsChanges.on("error", err => {
625625
await session.saveChanges();
626626
}
627627

628-
...
628+
// ...
629629
// dispose changes instance once you're done
630630
changes.dispose();
631631

@@ -635,8 +635,9 @@ changes.dispose();
635635

636636
#### Stream documents with ID prefix
637637
```javascript
638-
// stream() returns a Readable
639638
const userStream = await session.advanced.stream("users/");
639+
// stream() method returns a Readable
640+
640641
userStream.on("data", user => {
641642
// User { name: 'Anna', id: 'users/1-A' }
642643
});
@@ -649,16 +650,17 @@ userStream.on("error", err => {
649650
```javascript
650651
// create a query
651652
const query = session.query({ collection: "users" }).whereGreaterThan("age", 29);
652-
// can get query stats passing a stats callback to stream()
653+
653654
let stats;
654655
// stream() returns a Readable
656+
// get query stats passing a stats callback to stream() method
655657
const queryStream = await session.advanced.stream(query, _ => stats = _);
656658

657659
queryStream.on("data", user => {
658660
// User { name: 'Anna', id: 'users/1-A' }
659661
});
660662

661-
// or can get stats using an event listener
663+
// get stats using an event listener
662664
queryStream.once("stats", stats => {
663665
// { resultEtag: 7464021133404493000,
664666
// isStale: false,
@@ -687,7 +689,7 @@ const user = {
687689
await session.store(user, "users/1");
688690
await session.saveChanges();
689691

690-
// modify doc to create a new revision
692+
// modify the document to create a new revision
691693
user.name = "Roman";
692694
user.age = 40;
693695
await session.saveChanges();
@@ -708,18 +710,13 @@ const revisions = await session.advanced.revisions.getFor("users/1");
708710

709711
### Suggestions
710712
```javascript
711-
// Having data:
713+
// users collection
712714
// [ User {
713715
// name: 'John',
714716
// age: 30,
715717
// registeredAt: 2017-11-10T23:00:00.000Z,
716718
// kids: [Array],
717719
// id: 'users/1-A' },
718-
// User {
719-
// name: 'Stefanie',
720-
// age: 25,
721-
// registeredAt: 2015-07-29T22:00:00.000Z,
722-
// id: 'users/2-A' } ]
723720

724721
// and a static index like:
725722
class UsersIndex extends AbstractIndexCreationTask {
@@ -742,11 +739,7 @@ const suggestionQueryResult = await session.query({ collection: "users" })
742739

743740
## Using object literals for entities
744741

745-
In order to comfortably use object literals as entities set function getting collection name based on the content of the object - `store.conventions.
746-
findCollectionNameForObjectLiteral()`. This needs to be done *before* a `initialize()` call on `DocumentStore` instance. If you fail to do so, your entites will land up in *@empty* collection having an *UUID* for an ID.
747-
748-
For example here's a function using *collection* field to set collection name:
749-
742+
In order to comfortably use object literals as entities set function getting collection name based on the content of the object - `store.conventions.findCollectionNameForObjectLiteral()`. This needs to be done *before* an `initialize()` call on `DocumentStore` instance. If you fail to do so, your entites will land up in *@empty* collection having an *UUID* for an ID. E.g.
750743
```javascript
751744
store.conventions.findCollectionNameForObjectLiteral = entity => entity["collection"];
752745
```

src/Documents/Commands/FacetQueryCommand.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ export class FacetQueryCommand extends QueryCommand {
2121

2222
let body: string = null;
2323
this.result = await FacetQueryCommand.parseQueryResultResponseAsync(
24-
bodyStream, this._conventions, fromCache, this._typedObjectMapper, b => body = b);
24+
bodyStream, this._conventions, fromCache, b => body = b);
2525

2626
return body;
2727
}
@@ -30,7 +30,6 @@ export class FacetQueryCommand extends QueryCommand {
3030
bodyStream: stream.Stream,
3131
conventions: DocumentConventions,
3232
fromCache: boolean,
33-
mapper: TypesAwareObjectMapper,
3433
bodyCallback?: (body: string) => void): Promise<QueryResult> {
3534

3635
const resultsPromise = RavenCommandResponsePipeline.create<object[]>()
@@ -48,7 +47,7 @@ export class FacetQueryCommand extends QueryCommand {
4847

4948
const [results, includes, rest] = await Promise.all([resultsPromise, includesPromise, restPromise]);
5049
const rawResult = Object.assign({} as any, rest, { results, includes }) as QueryResult;
51-
const queryResult = mapper.fromObjectLiteral<QueryResult>(rawResult, {
50+
const queryResult = conventions.objectMapper.fromObjectLiteral<QueryResult>(rawResult, {
5251
typeName: QueryResult.name,
5352
nestedTypes: {
5453
indexTimestamp: "date",

src/Documents/Commands/GetConflictsCommand.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,17 @@ import { RavenCommand } from "../../Http/RavenCommand";
33
import { GetConflictsResult } from "./GetConflictsResult";
44
import { ServerNode } from "../../Http/ServerNode";
55
import * as stream from "readable-stream";
6+
import { DocumentConventions } from "../Conventions/DocumentConventions";
67

78
export class GetConflictsCommand extends RavenCommand<GetConflictsResult> {
89

910
private readonly _id: string;
11+
private readonly _conventions: DocumentConventions;
1012

11-
public constructor(id: string) {
13+
public constructor(id: string, conventions: DocumentConventions) {
1214
super();
1315
this._id = id;
16+
this._conventions = conventions;
1417
}
1518

1619
public get isReadRequest(): boolean {
@@ -34,7 +37,7 @@ export class GetConflictsCommand extends RavenCommand<GetConflictsResult> {
3437
let body: string = null;
3538
await this._defaultPipeline(_ => body = _).process(bodyStream)
3639
.then(results => {
37-
this.result = this._typedObjectMapper.fromObjectLiteral(results, {
40+
this.result = this._conventions.objectMapper.fromObjectLiteral(results, {
3841
nestedTypes: {
3942
"results[].lastModified": "Date"
4043
}

src/Documents/Commands/QueryCommand.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ export class QueryCommand extends RavenCommand<QueryResult> {
9191

9292
let body: string = null;
9393
this.result = await QueryCommand.parseQueryResultResponseAsync(
94-
bodyStream, this._conventions, fromCache, this._typedObjectMapper, b => body = b);
94+
bodyStream, this._conventions, fromCache, b => body = b);
9595

9696
return body;
9797
}
@@ -104,7 +104,6 @@ export class QueryCommand extends RavenCommand<QueryResult> {
104104
bodyStream: stream.Stream,
105105
conventions: DocumentConventions,
106106
fromCache: boolean,
107-
mapper: TypesAwareObjectMapper,
108107
bodyCallback?: (body: string) => void): Promise<QueryResult> {
109108

110109
const resultsPromise = parseDocumentResults(bodyStream, conventions, bodyCallback);
@@ -113,13 +112,14 @@ export class QueryCommand extends RavenCommand<QueryResult> {
113112

114113
const [results, includes, rest] = await Promise.all([resultsPromise, includesPromise, restPromise]);
115114
const rawResult = Object.assign({} as any, rest, { results, includes }) as QueryResult;
116-
const queryResult = mapper.fromObjectLiteral<QueryResult>(rawResult, {
117-
typeName: QueryResult.name,
118-
nestedTypes: {
119-
indexTimestamp: "date",
120-
lastQueryTime: "date"
121-
}
122-
}, new Map([[QueryResult.name, QueryResult]]));
115+
const queryResult = conventions.objectMapper
116+
.fromObjectLiteral<QueryResult>(rawResult, {
117+
typeName: QueryResult.name,
118+
nestedTypes: {
119+
indexTimestamp: "date",
120+
lastQueryTime: "date"
121+
}
122+
}, new Map([[QueryResult.name, QueryResult]]));
123123

124124
if (fromCache) {
125125
queryResult.durationInMs = -1;

src/Documents/Conventions/DocumentConventions.ts

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,8 @@ export class DocumentConventions {
7070
private _localEntityFieldNameConvention: CasingConvention;
7171
private _remoteEntityFieldNameConvention: CasingConvention;
7272

73-
private _entityObjectMapper: TypesAwareObjectMapper;
73+
private _objectMapper: TypesAwareObjectMapper;
7474

75-
private _entityJsonSerializer: JsonSerializer;
7675
private _useCompression;
7776

7877
public constructor() {
@@ -111,21 +110,20 @@ export class DocumentConventions {
111110
this._maxHttpCacheSize = 128 * 1024 * 1024;
112111

113112
this._knownEntityTypes = new Map();
114-
this._entityObjectMapper = new TypesAwareObjectMapper({
113+
this._objectMapper = new TypesAwareObjectMapper({
115114
dateFormat: DateUtil.DEFAULT_DATE_FORMAT,
116115
documentConventions: this
117116
});
118117

119-
this._entityJsonSerializer = JsonSerializer.getDefaultForEntities();
120118
this._useCompression = null;
121119
}
122120

123-
public get entityObjectMapper(): TypesAwareObjectMapper {
124-
return this._entityObjectMapper;
121+
public get objectMapper(): TypesAwareObjectMapper {
122+
return this._objectMapper;
125123
}
126124

127-
public set entityObjectMapper(value: TypesAwareObjectMapper) {
128-
this._entityObjectMapper = value;
125+
public set objectMapper(value: TypesAwareObjectMapper) {
126+
this._objectMapper = value;
129127
}
130128

131129
public get readBalanceBehavior(): ReadBalanceBehavior {
@@ -158,7 +156,7 @@ export class DocumentConventions {
158156
public deserializeEntityFromJson(documentType: ObjectTypeDescriptor, document: object): object {
159157
try {
160158
const typeName = documentType ? documentType.name : null;
161-
return this.entityObjectMapper.fromObjectLiteral(document, { typeName });
159+
return this.objectMapper.fromObjectLiteral(document, { typeName });
162160
} catch (err) {
163161
throwError("RavenException", "Cannot deserialize entity", err);
164162
}

src/Documents/DocumentStore.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ export class DocumentStore extends DocumentStoreBase {
103103
disposeChain
104104
.then(() => {
105105
if (this._multiDbHiLo) {
106-
return BluebirdPromise.resolve()
106+
return Promise.resolve()
107107
.then(() => this._multiDbHiLo.returnUnusedRange())
108108
.catch(err => this._log.warn("Error returning unused ID range.", err));
109109
}
@@ -115,6 +115,7 @@ export class DocumentStore extends DocumentStoreBase {
115115
return new BluebirdPromise((resolve, reject) => {
116116
let listenersExecCallbacksCount = 0;
117117
const listenersCount = this.listenerCount("afterDispose");
118+
118119
this.emit("afterDispose", () => {
119120
if (listenersCount === ++listenersExecCallbacksCount) {
120121
resolve();

src/Documents/Identity/Commands/NextHiloCommand.ts

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { RavenCommand } from "../../../Http/RavenCommand";
55
import { throwError } from "../../../Exceptions";
66
import { HttpRequestParameters } from "../../../Primitives/Http";
77
import * as stream from "readable-stream";
8+
import { DocumentConventions } from "../../Conventions/DocumentConventions";
89

910
export interface HiLoResult {
1011
prefix: string;
@@ -22,13 +23,15 @@ export class NextHiloCommand extends RavenCommand<HiLoResult> {
2223
private readonly _lastRangeAt: Date;
2324
private readonly _identityPartsSeparator: string;
2425
private readonly _lastRangeMax: number;
26+
private readonly _conventions: DocumentConventions;
2527

2628
public constructor(
2729
tag: string,
2830
lastBatchSize: number,
2931
lastRangeAt: Date,
3032
identityPartsSeparator: string,
31-
lastRangeMax: number) {
33+
lastRangeMax: number,
34+
conventions: DocumentConventions) {
3235
super();
3336

3437
if (!tag) {
@@ -44,6 +47,7 @@ export class NextHiloCommand extends RavenCommand<HiLoResult> {
4447
this._lastRangeAt = lastRangeAt;
4548
this._identityPartsSeparator = identityPartsSeparator;
4649
this._lastRangeMax = lastRangeMax;
50+
this._conventions = conventions;
4751
}
4852

4953
public createRequest(node: ServerNode): HttpRequestParameters {
@@ -67,11 +71,14 @@ export class NextHiloCommand extends RavenCommand<HiLoResult> {
6771
let body: string = null;
6872
await this._defaultPipeline(_ => body = _).process(bodyStream)
6973
.then(results => {
70-
this.result = this._reviveResultTypes(results, {
71-
nestedTypes: {
72-
lastRangeAt: "date"
73-
}
74-
});
74+
this.result = this._reviveResultTypes(
75+
results,
76+
this._conventions,
77+
{
78+
nestedTypes: {
79+
lastRangeAt: "date"
80+
}
81+
});
7582
});
7683
return body;
7784
}

src/Documents/Identity/HiloIdGenerator.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,12 @@ export class HiloIdGenerator {
8989

9090
protected _getNextRange(): Promise<void> {
9191
const hiloCmd = new NextHiloCommand(
92-
this._tag, this._lastBatchSize, this._lastRangeAt, this._identityPartsSeparator, this._range.maxId);
92+
this._tag,
93+
this._lastBatchSize,
94+
this._lastRangeAt,
95+
this._identityPartsSeparator,
96+
this._range.maxId,
97+
this._store.conventions);
9398
return this._store.getRequestExecutor(this._dbName).execute(hiloCmd)
9499
.then(() => {
95100
const result: HiLoResult = hiloCmd.result;
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
import { DocumentConventions } from "../Conventions/DocumentConventions";
2+
13
export interface IHiloIdGenerator {
24
//TODO ? nextId(...args: Array<object | string | string>): Promise<number>;
3-
generateDocumentId(...args: Array<object | string>): Promise<string>;
5+
generateDocumentId(...args: any[]): Promise<string>;
46

57
returnUnusedRange(): Promise<void>;
68
}

src/Documents/Operations/Indexes/GetIndexErrorsOperation.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export class GetIndexErrorsOperation implements IMaintenanceOperation<IndexError
1717
}
1818

1919
public getCommand(conventions: DocumentConventions): RavenCommand<IndexErrors[]> {
20-
return new GetIndexErrorsCommand(this._indexNames);
20+
return new GetIndexErrorsCommand(this._indexNames, conventions);
2121
}
2222

2323
public get resultType(): OperationResultType {
@@ -28,10 +28,12 @@ export class GetIndexErrorsOperation implements IMaintenanceOperation<IndexError
2828

2929
export class GetIndexErrorsCommand extends RavenCommand<IndexErrors[]> {
3030
private readonly _indexNames: string[];
31+
private readonly _conventions: DocumentConventions;
3132

32-
public constructor(indexNames: string[]) {
33+
public constructor(indexNames: string[], conventions: DocumentConventions) {
3334
super();
3435
this._indexNames = indexNames;
36+
this._conventions = conventions;
3537
}
3638

3739
public createRequest(node: ServerNode): HttpRequestParameters {
@@ -62,7 +64,7 @@ export class GetIndexErrorsCommand extends RavenCommand<IndexErrors[]> {
6264
let body: string = null;
6365
await this._defaultPipeline(_ => body = _).process(bodyStream)
6466
.then(results => {
65-
this.result = this._reviveResultTypes(results, typeInfo)["results"];
67+
this.result = this._reviveResultTypes(results, this._conventions, typeInfo)["results"];
6668
});
6769
return body;
6870
}

0 commit comments

Comments
 (0)