Skip to content
Open
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
8 changes: 7 additions & 1 deletion README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -203,8 +203,14 @@ let posts = this.datastore.peekAll(Post);


#### Retrieving a Single Record
Use `findOne()` to retrieve a record by its type and ID including metadata:
```typescript
this.datastore.findOne(Post, '1').subscribe(
(post: JsonApiQueryData<Post>) => console.log(post.getModel())
);
```

Use `findRecord()` to retrieve a record by its type and ID:
If you dont need Metadata you can use `findRecord()` to retrieve a record by its type and ID:

```typescript
this.datastore.findRecord(Post, '1').subscribe(
Expand Down
24 changes: 20 additions & 4 deletions src/models/json-api-query-data.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
export class JsonApiQueryData<T> {
constructor(protected jsonApiModels: Array<T>, protected metaData?: any) {}
constructor(protected data: Array<T> | T, protected meta?: any) {}

public getModels(): T[] {
return this.jsonApiModels;
public getModels() : T[] {
if (!(this.data instanceof Array)) {
throw new Error('Data is not an array.');
}

return this.data;
}

public getModel() : T {
if (this.data instanceof Array) {
throw new Error('Data is not an object.');
}

return this.data;
}

public getData(): T[] | T {
return this.data;
}

public getMeta(): any {
return this.metaData;
return this.meta;
}
}
24 changes: 24 additions & 0 deletions src/services/json-api-datastore.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,30 @@ describe('JsonApiDatastore', () => {
});
});

it('should get author with custom metadata', () => {
backend.connections.subscribe((c: MockConnection) => {
c.mockRespond(new Response(
new ResponseOptions({
body: JSON.stringify({
data: getAuthorData(),
meta: {
dates: {
generatedAt: 1518950882
}
}
})
})
));
});

datastore.findOne(Author, '1').subscribe((document) => {
expect(document.getModel()).toBeDefined();
expect(document.getModel().id).toBe(AUTHOR_ID);
expect(document.getModel().date_of_birth).toEqual(parse(AUTHOR_BIRTH));
expect(document.getMeta().meta.dates.generatedAt).toEqual(1518950882);
});
});

it('should generate correct query string for array params with findRecord', () => {
backend.connections.subscribe((c: MockConnection) => {
const decodedQueryString = decodeURI(c.request.url).split('?')[1];
Expand Down
47 changes: 41 additions & 6 deletions src/services/json-api-datastore.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,39 @@ export class JsonApiDatastore {
.catch((res: any) => this.handleError(res));
}

findRecord<T extends JsonApiModel>(
private fetchRecord<T extends JsonApiModel>(
modelType: ModelType<T>,
id: string,
params?: any,
headers?: Headers,
customUrl?: string
): Observable<T> {
customUrl?: string,
): Observable<Response> {
const options: RequestOptions = this.getOptions(headers);
const url: string = this.buildUrl(modelType, params, id, customUrl);

return this.http.get(url, options)
return this.http.get(url, options);
}

findOne<T extends JsonApiModel>(
modelType: ModelType<T>,
id: string,
params?: any,
headers?: Headers,
customUrl?: string
): Observable<JsonApiQueryData<T>> {
return this.fetchRecord(modelType, id, params, headers, customUrl)
.map((res) => this.extractRecordData(res, modelType, true))
.catch((res: any) => this.handleError(res));
}

findRecord<T extends JsonApiModel>(
modelType: ModelType<T>,
id: string,
params?: any,
headers?: Headers,
customUrl?: string
): Observable<T> {
return this.fetchRecord(modelType, id, params, headers, customUrl)
.map((res) => this.extractRecordData(res, modelType))
.catch((res: any) => this.handleError(res));
}
Expand Down Expand Up @@ -135,7 +157,11 @@ export class JsonApiDatastore {
}

return httpCall
.map((res) => [200, 201].indexOf(res.status) !== -1 ? this.extractRecordData(res, modelType, model) : model)
.map(
(res) => [200, 201].indexOf(res.status) !== -1
? this.extractRecordData(res, modelType, false, model)
: model
)
.catch((res) => {
if (res == null) {
return Observable.of(model);
Expand Down Expand Up @@ -281,7 +307,12 @@ export class JsonApiDatastore {
return new modelType(this, data);
}

protected extractRecordData<T extends JsonApiModel>(res: Response, modelType: ModelType<T>, model?: T): T {
protected extractRecordData<T extends JsonApiModel>(
res: Response,
modelType: ModelType<T>,
withMeta = false,
model?: T
): T | JsonApiQueryData<T> {
const body: any = res.json();

if (!body) {
Expand All @@ -307,6 +338,10 @@ export class JsonApiDatastore {
this.addToStore(deserializedModel);
}

if (withMeta && withMeta === true) {
return new JsonApiQueryData(deserializedModel, this.parseMeta(body, modelType));
}

return deserializedModel;
}

Expand Down