在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):ember-graphql/ember-apollo-client开源软件地址(OpenSource Url):https://github.com/ember-graphql/ember-apollo-client开源编程语言(OpenSource Language):JavaScript 91.6%开源软件介绍(OpenSource Introduction):ember-apollo-clientUse @apollo/client and GraphQL from your Ember app. This addon is battle tested: it has been used to build several large apps. As such, we've solved real-world problems such as reliable testing and preventing resource leaks by unsubscribing from watch queries. Installation
This should also automatically install Install the Apollo Client Developer tools for Chrome for a great GraphQL developer experience! Compatibility
For compatibility with Ember versions below 3.4, use version 1.x. For compatibility with Apollo Client v1 or v2, use version 1.x or 2.x of this addon. ConfigurationRuntime configurationIn your app's let ENV = {
...
apollo: {
apiURL: 'https://test.example/graphql',
// Optionally, set the credentials property of the Fetch Request interface
// to control when a cookie is sent:
// requestCredentials: 'same-origin', // other choices: 'include', 'omit'
},
...
} Additional configuration of the ApolloClient can be done by extending the Apollo
service and overriding the Build time configurationIn your app's module.exports = function(defaults) {
let app = new EmberApp(defaults, {
emberApolloClient: {
keepGraphqlFileExtension: false
}
});
return app.toTree();
};
Example: import myQuery from 'my-app/queries/my-query.graphql'; DependenciesThis addon uses ember-auto-import to import dependencies. This addon does not exposes any dependencies directly to your application, so if you desire any additional graphql or apollo dependencies, install them with npm/yarn and import as desired. Here are some useful packages: Make sure to use ember-auto-import in your application to import these additional packages. Peer DependenciesThis addon has a peer dependency of: UsageFetching dataGraphQL queries should be placed in external files, which are automatically made available for import:
query human($id: String!) {
human(id: $id) {
name
}
} You can also use the import gql from "graphql-tag";
const query = gql`
query human($id: String!) {
human(id: $id) {
name
}
}
`;
Within your routes, you can query for data using the
import Route from "@ember/routing/route";
import { queryManager } from "ember-apollo-client";
import query from "my-app/gql/queries/human.graphql";
export default Route.extend({
apollo: queryManager(),
model(params) {
let variables = { id: params.id };
return this.apollo.watchQuery({ query, variables }, "human");
}
}); This performs a If a subsequent query (such as a mutation) happens to fetch the same data while this query's subscription is still active, the object will immediately receive the latest attributes (just like ember-data). Please note that when using You can instead use If you need to access the Apollo Client ObservableQuery,
such as for pagination, you can retrieve it from a import Route from "@ember/routing/route";
import { getObservable, queryManager} from "ember-apollo-client";
export default Route.extend({
apollo: queryManager(),
model() {
let result = this.apollo.watchQuery(...);
let observable = getObservable(result);
observable.fetchMore(...) // utilize the ObservableQuery
...
}
}); See the detailed query manager docs for more details on usage, or the Apollo service API if you need to use the service directly. GraphQL SubscriptionsGQL Subscriptions allow a client to subscribe to specific queries they are interested in tracking. The syntax for doing this is similar to
Creating your subscription
subscription {
newHuman() {
name
}
} Subscribing from inside a route
import Route from '@ember/routing/route';
import { queryManager } from 'ember-apollo-client';
import query from 'app/gql/subscriptions/new-human';
import { addListener, removeListener } from '@ember/object/events';
const handleEvent = event => alert(`${event.name} was just born!`);
export default Route.extend({
apollo: queryManager(),
model() {
return this.get('apollo').subscribe({ query }, 'human');
},
setupController(controller, model) {
addListener(model, 'event', handleEvent);
},
resetController(controller, isExiting, transition) {
if (isExiting) {
removeListener(controller.model, 'event', handleEvent);
}
}
}); The big advantage of using the Enabling Websockets While this library should work w/ any back-end implementation, here's an example with Authenticated Phoenix + Absinthe:
import ApolloService from 'ember-apollo-client/services/apollo';
import { inject as service } from '@ember/service';
import { Socket } from 'phoenix';
import { createAbsintheSocketLink } from '@absinthe/socket-apollo-link';
import AbsintheSocket from '@absinthe/socket';
class OverriddenApollo extends ApolloService {
@service
session;
link() {
const socket = new Socket("ws://socket-url", {
params: { token: this.get('session.token') },
});
const absintheSocket = AbsintheSocket.create(socket);
return createAbsintheSocketLink(absintheSocket);
}
} Note: This will switch all gql communication to use websockets versus
import ApolloService from 'ember-apollo-client/services/apollo';
import { inject as service } from '@ember/service';
import { Socket } from 'phoenix';
import { split } from '@apollo/client';
import { getMainDefinition } from '@apollo/client/utilities';
import { createAbsintheSocketLink } from '@absinthe/socket-apollo-link';
import AbsintheSocket from '@absinthe/socket';
class OverriddenApollo extends ApolloService {
@service
session;
link() {
let httpLink = super.link();
const socket = new Socket("ws://socket-url", {
params: { token: this.get('session.token') },
});
const socketLink = createAbsintheSocketLink(AbsintheSocket.create(socket));
return split(
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
socketLink,
httpLink
);
}
} Note: You will need to add the following dependencies to your project: yarn add -D @apollo/client
yarn add -D @absinthe/socket
yarn add -D @absinthe/socket-apollo-link Mutations and FragmentsYou can perform a mutation using the The following example shows both mutations and fragments in action:
fragment ReviewFragment on Human {
stars
commentary
}
#import ReviewFragment from 'my-app/gql/fragments/review-fragment.graphql'
mutation createReview($ep: Episode!, $review: ReviewInput!) {
createReview(episode: $ep, review: $review) {
review {
...ReviewFragment
}
}
}
import Route from "@ember/routing/route";
import { inject as service } from "@ember/service";
import mutation from "my-app/gql/mutations/create-review.graphql";
export default Route.extend({
apollo: service(),
actions: {
createReview(ep, review) {
let variables = { ep, review };
return this.get("apollo").mutate({ mutation, variables }, "review");
}
}
}); Query manager API
Apollo service APIYou should not need to use the Apollo service directly for most regular
usage, instead utilizing the The
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论