diff --git a/examples/hello-world/client/main.html b/examples/hello-world/client/main.html index 75cfd2c4a..0eb5bc90b 100644 --- a/examples/hello-world/client/main.html +++ b/examples/hello-world/client/main.html @@ -8,7 +8,7 @@

Add new

List

diff --git a/examples/hello-world/client/main.ts b/examples/hello-world/client/main.ts index d54aab110..b1bfe6468 100644 --- a/examples/hello-world/client/main.ts +++ b/examples/hello-world/client/main.ts @@ -23,7 +23,7 @@ import ApolloClient, { import gql from 'apollo-client/gql'; import { - graphQLResult + graphQLResult, } from 'graphql'; const client = new ApolloClient({ @@ -89,9 +89,10 @@ const client = new ApolloClient({ }, }) class Main { - users: Observable; - firstName: string; - lastName: string; + public addUser: Function; + public users: Observable; + public firstName: string; + public lastName: string; public newUser() { this.addUser(this.firstName) diff --git a/src/apolloQueryPipe.ts b/src/apolloQueryPipe.ts index c20059fcf..d7b208703 100644 --- a/src/apolloQueryPipe.ts +++ b/src/apolloQueryPipe.ts @@ -4,12 +4,29 @@ import { Pipe, } from '@angular/core'; +import { + values, + isEmpty, + isObject, +} from 'lodash'; + @Pipe({ name: 'apolloQuery', }) export class ApolloQueryPipe { public transform(obj: any, name: string = '') { - if (obj && obj.data && name !== '' && obj.data[name]) { + if (!isObject(obj)) { + return; + } + + // an empty object by default + obj = (obj || {}); + + if (isEmpty(name)) { + return values(obj.data)[0]; + } + + if (obj.data) { return obj.data[name]; } } diff --git a/tests/apolloQueryPipe.ts b/tests/apolloQueryPipe.ts index be5aca95d..db42f41ac 100644 --- a/tests/apolloQueryPipe.ts +++ b/tests/apolloQueryPipe.ts @@ -7,14 +7,35 @@ describe('ApolloQueryPipe', () => { pipe = new ApolloQueryPipe(); }); - it('should capitalize all words in a string', () => { - const object = { + it('should return nothing if first argument is not an object', () => { + expect(pipe.transform('test')).toBeUndefined(); + }); + + it('should return nothing on empty object', () => { + expect(pipe.transform({})).toBeUndefined(); + }); + + it('should return nothing on empty data', () => { + expect(pipe.transform({ + data: {}, + })).toBeUndefined(); + }); + + it('should use the first property of data if name is not defined', () => { + expect(pipe.transform({ data: { - foo: 'bar', + foo: 'foo', + bar: 'bar', }, - }; - const result = pipe.transform(object, 'foo'); + })).toEqual('foo'); + }); - expect(result).toEqual(object.data.foo); + it('should use a property where key matches name', () => { + expect(pipe.transform({ + data: { + foo: 'foo', + bar: 'bar', + }, + }, 'bar')).toEqual('bar'); }); });