npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ember-graph-data

v0.2.1

Published

GraphQL & ember-data integration for ambitious web apps.

Downloads

3

Readme

npm npm version Ember Observer Score Travis Code Climate

ember-graph-data

GraphQL & EmberData integration for ambitious apps!

Installation

Ensure you have ember-data installed:

ember install ember-data

And then:

ember install ember-graph-data

Minimal setup

app/adapters/application.js

import GraphAdapter from 'ember-graph-data/adapter'

export default GraphAdapter.extend({
  host:       'http://localhost:4000', // your API host
  namespace:  'api/v1/graph',          // your API namespace
})

app/serializers/application.js

import GraphSerializer from 'ember-graph-data/serializer'

export default GraphSerializer.extend()

Usage

app/routes/posts.js

import Route    from '@ember/routing/route'
import query    from 'my-app/gql/queries/posts'
import mutation from 'my-app/gql/mutations/post-create'

export default Route.extend({
  model(params) {
    let variables = { page: 1 }
    return this.store.graphQuery({query, variables})
  }

  actions: {
    createPost(variables) {
      return this.store.graphMutate({mutation, variables})
    }
  }
})

Transport layer

Sometimes json is not sufficient in expressing our application needs. File upload is a good example. Of course it can be done by sending them in base64 form, but it is extremely ineffective (particularly with big files). Or we can prepare special non-graphql endpoint on the server side. None of the above seems to be a good solution. That's why ember-graph-data supports sending graphql queries and mutations in json and multipart form. In multipart mode, adapter will serialize any file encountered in variables as another field in multipart request.

app/routes/images.js

import Route    from '@ember/routing/route'
import query    from 'my-app/gql/queries/images'
import mutation from 'my-app/gql/mutations/image-create'

export default Route.extend({
  model(params) {
    let variables = { page: 1 }
    return this.store.graphQuery({query, variables})
  }

  actions: {
    createImage(file) {
      let variables = { file }
      let options =   { transport: 'multipart' }
      return this.store.graphMutate({mutation, variables, options})
    }
  }
})

On the server side it was tested with:

Adapter

headers support

app/adapters/application.js

import GraphAdapter from 'ember-graph-data/adapter'
import {computed} from '@ember/object'
import {inject as service} from '@ember/service'

export default GraphAdapter.extend({
  session: service(),
  headers: computed('session.jwt', function() {
    return {
      // authorize reuests
      'Authorization': `Bearer ${this.get('session.jwt')}`,
      // maybe provide localized output?
      'Content-Language': 'pl'
      // etc
    }
  })
})

handle error & handle response

app/adapters/application.js

import GraphAdapter from 'ember-graph-data/adapter'
import {inject as service} from '@ember/service'

export default GraphAdapter.extend({
  eventBus: service(),

  handleGraphError(error, {query, variables}) {
    let errors = error.response.errors || []
    if (errors.every((err) => err.code !== 'unauthorized')) return error
    // example only. Do whatever you want :)
    this.get('eventBus').dispatch({type: 'UNAUTHORIZED'})
  }

  // Hook after successful request
  handleGraphResponse(response, {query, variables}) {
    return response
  },
}

additional config

You can configure behaviour of graph adapter. Below options are defaults. app/adapters/application.js

import GraphAdapter from 'ember-graph-data/adapter'
export default GraphAdapter.extend({
  graphOptions: {
    /* appends __typename field to every object in query.
       This is used for model lookup.
    */
    addTypename: true,
  },
})

Serializer

custom modelName mapping

In case when __typename field from API does not directly reflect your DS model names, you can customize it in modelNameFromGraphResponse: app/serializers/application.js

import GraphSerializer from 'ember-graph-data/serializer'

export default GraphSerializer.extend({
  modelNameFromGraphResponse(response) {
    return response.__typename
  }
}

custom modelName namespace separator

Proper handling namespaced DS models requires __typename to contain namespace separator. For instance, model user/blog-post will be looked-up correctly, for following __typename values:

  • user--blog-post
  • User--BlogPost
  • user--Blog-Post
  • User--blogPost
  • User--blog_Post
  • user/blog-post
  • user/blog_post
  • User/BlogPost

It is not adviced to apply such incoherency in a naming convetion, but still it will be handled. ember-graph-data accepts -- and / defaultly as a namespace separator. You can adjust that to your needs like this:

app/serializers/application.js

import GraphSerializer from 'ember-graph-data/serializer'

export default GraphSerializer.extend({
  modelNameNamespaceSeparator: '$$$'
}

And from now, user$$$blog-post and other variations will be recognized correctly.

Automatic model lookup

GraphSerializer automatically lookups and instantiates models for you. This process relies on __typename field which is returned from GraphQL server in every object. Lets make some assumptions:

You have defined following models:

app/models/user-role.js

import DS from 'ember-data'

const {
  Model,
  attr
} = DS

export default Model.extend({
  name: attr(),
  code: attr()
})

app/models/user.js

import DS from 'ember-data'

const {
  Model,
  attr,
  belongsTo
} = DS

export default Model.extend({
  firstName:  attr(),
  lastName:   attr(),
  email:      attr(),
  role:       belongsTo('user-role', { async: false })
});

You have sent following query to the GraphQL server:

app/graph/queries/users.graphql

query users {
  users {
    {
      id
      firstName
      lastName

      role {
        id
        name
        code
      }
    }
  }
}

In result of above actions, you will get an array of User models. You can also inspect those models in a Data tab of Ember inspector. Moreover, each User will have association role properly set. Simple, yet powerful.

Fastboot

Fastboot is supported by default.

enhanced rehydration

Moreover, this addon supports automatic requests caching in Shoebox. Thanks to this, application does not need to refetch already gathered data on the browser side. Mechanics of this process is provided by ember-cached-shoe. More details to be found in this addon README.