Code Monkey home page Code Monkey logo

ember-graphql-adapter's Introduction

Ember Data GraphQL Adapter

Npm Version Code Climate Circle CI Ember Observer Score Greenkeeper badge

A Ember CLI adapter for using GraphQL with Ember Data.

Installation

ember install ember-graphql-adapter

Usage

Create your adapter first

// app/adapters/post.js
import GraphQLAdapter from 'ember-graphql-adapter';

export default GraphQLAdapter.extend({
  endpoint: 'http://localhost:3000/graph'
});

Now define your serializer

// app/serializers/post.js
import { Serializer } from 'ember-graphql-adapter';

export default Serializer.extend({});

And you're done!

Features

  • Queries and mutations are automatically generated for you
  • Field aliases are supported
  • Belongs to relationships are fully supported
  • Has many relationships are fully supported
  • Async relationships and request coalescing is supported with coalesceFindRequests: true

Rails Example

By using the fantastic graphql gem, you can expose your relational database as a GraphQL endpoint.

We start by creating a new type

# app/models/graph/post_type.rb
module Graph
  PostType = GraphQL::ObjectType.define do
    name "Post"
    description "A post"

    field :id, types.ID
    field :name, types.String
  end
end

Then we create the query type

# app/models/graph/query_type.rb
module Graph
  QueryType = GraphQL::ObjectType.define do
    name "Query"
    description "The query root of this schema"

    field :post, PostType do
      argument :id, !types.ID, "The ID of the post"
      resolve -> (_object, arguments, _context) do
        Post.find(arguments[:id])
      end
    end
  end
end

After that, it's time for the mutation type

# app/models/graph/mutation_type.rb
module Graph
  MutationType = GraphQL::ObjectType.define do
    name "Mutation"
    description "Mutations"

    field :postCreate, PostType do
      argument :name, !types.String, "The post name"
      resolve -> (_object, arguments, _context) do
        Post.create(name: arguments[:name])
      end
    end
  end
end

Now, we can build the whole schema

# app/models/graph/schema.rb
module Graph
  Schema = GraphQL::Schema.define do
    query Graph::QueryType
    mutation Graph::MutationType
  end
end

In the controller we just delegate to the GraphQL schema

# app/controllers/graph_controller.rb
class GraphController < ApplicationController
  def execute
    render json: ::Graph::Schema.execute(
      params.fetch("query"),
      context: {} # you can pass the current_user here
    )
  end
end

Finally, we just expose the GraphQL endpoint in the route

# config/routes.rb
get 'graph', to: 'graph#execute'

And that's it!

Developing

Installation

  • git clone https://github.com/alphasights/ember-graphql-adapter.git
  • yarn install

Running

  • yarn start

Running Tests

  • yarn run ember test -- --server

Building

  • yarn build

ember-graphql-adapter's People

Contributors

arkham avatar delkopiso avatar ember-tomster avatar farisj avatar greenkeeper[bot] avatar jamestsaoas avatar jjbohn avatar pedrovereza avatar rduarte-as avatar terminalstar avatar willrax avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ember-graphql-adapter's Issues

Introduction to `ember-graphql-adapter` at Global Ember Meetup

Hi there, would you someone familiar with the project would be open to giving an "Introduction to ember-graphql-adapter" lightning talk at an upcoming Global Ember Meetup in the beginning of next year? We'll edit the video and give you video that you can embed into the addon's README. You can see an example of other introduction videos here https://vimeo.com/album/3607049

The talk usually covers:

  1. What's use case for the addon?
  2. How to get stated using it?
  3. What should the user be aware of?

Error Handling

The way we are handling GraphQL errors is causing issues when communicating on the front end and running respective tests.

@Arkham

README Show graphql syntax used

In your readme, it would be helpful to see the graphql sybtax that the adapters are trying to use. This will help out understand how to use for our needs.

Something like this

query
{
  Media(search: "Dragonball") {
    title {
      userPreferred
    },
    description
  }
} 

Multiple hasMany relationships generate wrong (nested) query

Given the model:

export default Model.extend({
  name: attr('string'),
  parents: DS.hasMany('node'),
  children: DS.hasMany('node')
});

The adapter generates the following query:

query node {
  node(id: "my_node_id") {
    id
    name
    parents {
      id
      name
      children {
        id
        name
      }
    }
  }
}

This seems to me to be faulty behavior, as the children should not be nested within the parents but rather be on the same level.

An in-range update of ember-ajax is breaking the build 🚨

Version 3.1.1 of ember-ajax was just published.

Branch Build failing 🚨
Dependency ember-ajax
Current Version 3.1.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

ember-ajax is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests failed on CircleCI (Details).

Commits

The new version differs by 34 commits.

  • 196b10f v3.1.1
  • 22f63a0 fix: use assign instead of deprecated merge
  • 3bcd571 chore(deps): update
  • 829d82d chore(ci): run tests against Ember 2.12+
  • 46b7ba1 chore: remove reference to ic-ajax
  • 826d4c3 chore: remove reference to Ember 1.13
  • 6694fb1 chore(docs): update README
  • 3a25d71 fix: don't append leading '/' when building url
  • f71854f refactor: convert to TypeScript
  • 23705b9 chore(deps): install and configure TypeScript
  • 31ee07a fix: make FastBoot test more reliable
  • b96b65f test: add FastBoot test
  • 2f58087 fix: correctly import najax for FastBoot
  • ad730f9 chore(ci): update node version
  • d1990ea fix: clean up some deprecation warnings

There are 34 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Create a demo app

We should do like a TodoMVC demo with a Rails GraphQL backend. Something that we could make a deploy to heroku button for and put all the code out there for people to see how to rig everything up. The README is a good starting place, but it'd be nice to go further with it.

Full object graph always requested?

We're seeing that all of the relationships are passed through, which doesn't seem like it jives with GraphQL as a "only what the client needs" query language.

Is there a way I'm not seeing, or plans to be able, to specify which fields should be returned?

Thanks!

inline fragments support?

http://graphql.org/learn/queries/#inline-fragments

I'm trying to build a query that looks something like this:

{
  findByVal_ProductLookup(val: "490441202902") {
    type: __typename
    ... on BARCODE {
      brcdVal: val
      someIds {
        someIdVal: val
        description
        primaryImage
        variation
      }
    }
  }
}

it would be great to see some more complex examples of the ember implementation.

Support for aliases?

Documentation on how to alias models and fields would be really helpful. I think there's a way with ember-graphql-adapter but it's unclear.

For example, say my graph has a type foo, but I want to use bar instead, what do I do?

Question regarding added alias for relationships

Hi,

I see from this integration test that:

  Post.reopen({
    postCategory: DS.belongsTo('postCategory', { async: false }),
    comments: DS.hasMany('comment', { async: false }),
    topComments: DS.hasMany('comment', { async: false })
  });

results in the following query in the test:

query author {
  author(id: "1") { 
    id name posts {
      id name 
      postCategory { id name }
      comments { id name }
      topComments: comments { id name }   # <- question is regarding this
    } 
    profile { id age }
  } 
}

I'm a bit puzzled by the field comments being queried twice and aliased as topComments once. As I understand it both Post.comments and Post.topComments is of type Comment, but when querying the the server why do we query the comments for both properties?

I think the expected behaviour would be just to drop the alias and ask the server for it's topComments field, but I'm quite new to GraphQL as I started working on it today, so I may be wrong here :-)

(I do understand that we can give arguments when query comments and thus alias may be appropriate to use, but that doesn't seem to be the case here.)

Constructs incorrect query when gathering a collection that contains a single object.

Given an ember model:

export default DS.Model.extend({
resources: DS.hasMany('resources', async: true)
});

In the case where resources is [1], the adapter assumes that the graphql api has the singular type available, and you can end up getting an error similar to:

    {"0"=>"Field 'resource' doesn't exist on type 'Query'"}

This means that to make this workable, you need to make sure the API has both the singular and plural way of accessing the resource which can be quite verbose.

Can't Identify Input type from server

I am trying to write a mutation to my GraphQL server and I keep getting an error:
{"errors":[{"message":"Field "userCreate" argument "user" of type "UserInput!" is required but not provided.","locations":[{"line":1,"column":24}]}]}
And the error in the console is as follows:
TypeError: Cannot read property 'user' of undefined

Is it possible to push data into the store using pushPayload?

I've been unable to get this owkring using the documentation surrounding pushPayload on a model that this adapter is being used for. I keep getting an error Error: Assertion Failed: Encountered a resource object with an undefined type (resolved resource using DS.JSONAPISerializer) also I get WARNING: heuristic fragment matching going on!.

Thanks.

Request only fetches ID

User Model

import DS from 'ember-data';

export default DS.Model.extend({
  email: DS.String,
  firstname: DS.String,
  lastname: DS.String
});

adapter

import GraphQLAdapter from 'ember-graphql-adapter';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
import ENV from 'appmin/config/environment';

export default GraphQLAdapter.extend(DataAdapterMixin, {
  authorizer: 'authorizer:oauth2',
  endpoint: `${ENV.host}/graphql`
});

Route model hook

model() {
  return get(this, 'store').findAll('user');
}

Query

query users { users { id } }

Why doesnt it query email, firstname and lastname?

GET supports only query operation

I'm trying to use your adapter, but I'm getting a this error with a mutation query:

account.js:17 createBankAccount Error: Error: Ember AJAX Request GET http://localhost:3000/graphql returned a 405
Payload (Empty Content-Type)
"GET supports only query operation"

This is the request:

context:Class {store: Class, __ember1524240476438: null}
data: {query: "mutation bankAccountCreate { bankAccount: bankAcco…r thirdParty thirdPartyPaymentAccount visible } }"}
dataType: "json"
type: "GET"

It's strange to me that a mutation is a GET, rather than a POST, but I assume running a query with a mutation what Apollo needs to run the correct resolvers? Regardless, my request is denied.

I've set this up using a createRecord method and then running save:

async createBankAccount(options) {
  const bankAccount = this.store.createRecord('bankAccount', options);
  try {
    await bankAccount.save();
  } catch (e) {
    console.warn(`createBankAccount Error: ${e}`)
  }
},

Readme issue

After installing as described in the Readme I found I had to change the names of the adapter and serializer from GraphQLAdapter to Adapter and from GraphQLSerilizer to Serializer.

Those original names aren't defined on the ember-graphql-adapter.

Compiler should use normalizeCase function from Serializer

Currently, when constructing the queries to send to the server, the compiler uses the adapters normalizeCase function. If the server is sending attributes underscored and ember expects them camelCased, overwriting the normalizeCase function in the adapter will cause the query to succeed but multi-word attributes to not display in the ember app. To get it working I had to do something like the following in my adapter:

compile(store, type, options) {
    options['normalizeCaseFn'] = this.compileNormalizeCase;
    return Compiler.compile(type, store, options);
  },
  compileNormalizeCase: function(string) {
    return underscore(string);
  }

and in the serializer:

normalizeCase(string) {
    return underscore(string);
  }

Since the normalizeCase function in the serializer is what is normally expected to be sent to the server and the normalizeCase on the adapter is used for retrieving data from the server it would make more sense to use the serializers normalizeCase function instead of the adapters.

options['normalizeCaseFn'] = this.normalizeCase;

Update to latset ember-cli-babel (support node 8)

Trying to install ember-graphql-adapter in a new ember project I get the following error:
$ yarn add ember-graphql-adapter

  yarn add v0.27.5
  [1/4] Resolving packages...
  [2/4] Fetching packages...
  error [email protected]: The engine "node" is incompatible with this module. Expected version "^4.5 || 6.* || 7.*".
  error Found incompatible module
  info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command

it looks like this is caused by the dependency to [email protected] which doesn't work with v8 - 6.8.2 does.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.