Skip to content

Instantly share code, notes, and snippets.

@ariutta
Last active July 12, 2016 21:09
Show Gist options
  • Save ariutta/325744a8803e2cfde129 to your computer and use it in GitHub Desktop.
Save ariutta/325744a8803e2cfde129 to your computer and use it in GitHub Desktop.
GraphQL vs. REST vs. TypeScript interfaces

We want to run the equivalent of the following, getting name, age and friends' name(s):

GET https://example.org/users/1

With GraphQL, we can use user.graphql to get the following:

      { 
        id: 'https://example.org/users/1',
        name: 'Jane Doe',
        friends: [
          { name: 'Sandy Mienza' }
        ]
      }

With Falcor, I think it would work like this:

var model = new falcor.Model({
  cache: {
    peopleById: {
      'https://example.org/users/1': { 
        id: 'https://example.org/users/1',
        name: 'Jane Doe',
        friends: [
          { $type: 'ref', value: ['peopleById', 'https://example.org/users/2'] }
        ]
      },
      'https://example.org/users/2': {
        id: 'https://example.org/users/2',
        name: 'Sandy Mienza',
        age: 40,
        friends: [
          { $type: 'ref', value: ['peopleById', 'https://example.org/users/1'] },
          { $type: 'ref', value: ['peopleById', 'https://example.org/users/3'] }
        ]
      },
      'https://example.org/users/3': {
        id: 'https://example.org/users/3',
        name: 'Mike Lee',
        age: 40,
        friends: [
          { $type: 'ref', value: ['peopleById', 'https://example.org/users/2'] }
        ]
      }
    },
    users: [
        { $type: 'ref', value: ['peopleById', 'https://example.org/users/1'] },
        { $type: 'ref', value: ['peopleById', 'https://example.org/users/2'] },
        { $type: 'ref', value: ['peopleById', 'https://example.org/users/3'] }
    ]
  }
});

// prints the following:
// {"json":{"users":{"0":{"name":"Jane Doe"}}}}
model.
  get(['users', 0, ['name', 'age']]).
  subscribe(pathValue => console.log(JSON.stringify(result)));

// prints the following:
// { path: [['users', 0, 'friends'], { from: 0, to: 10 }, 'name'], value: ['Sandy Mienza'] }
model.
  get(['users', 0, 'friends'], { from: 0, to: 10 }, 'name').
  toPathValues().
  subscribe(pathValue => console.log(JSON.stringify(pathValue)));

https://jsfiddle.net/obg0b8x4/

var Iri: string;
interface Person {
id: Iri,
name: string;
}
interface User extends Person {
age?: number;
friends: Person[];
}
{
user(id: 1) {
name
age
friends {
name
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment