daddy/client/src/util/daddy.ts

115 lines
2.6 KiB
TypeScript
Raw Normal View History

2020-07-16 20:21:58 +02:00
import ApolloClient, { DefaultOptions } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { split } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
2020-07-16 20:21:58 +02:00
import { getMainDefinition, variablesInOperation } from 'apollo-utilities';
import gql from 'graphql-tag';
2020-07-16 20:21:58 +02:00
import { ProfileChanges } from '../store/actions/profile';
2020-06-15 18:10:06 +02:00
export class UnauthorizedError extends Error {
constructor(...args: any[]) {
super(...args)
Object.setPrototypeOf(this, UnauthorizedError.prototype);
}
}
let client: DaddyClient
export function getClient(graphQLEndpoint: string, subscriptionEndpoint: string): DaddyClient {
if (!client) {
client = new DaddyClient(graphQLEndpoint, subscriptionEndpoint);
}
return client;
}
2020-06-15 18:10:06 +02:00
export class DaddyClient {
gql: ApolloClient<InMemoryCache>
constructor(graphQLEndpoint: string, subscriptionEndpoint: string) {
const wsLink = new WebSocketLink({
uri: subscriptionEndpoint,
options: {
reconnect: true
}
});
const httpLink = new HttpLink({
uri: graphQLEndpoint,
fetchOptions: {
mode: 'cors',
credentials: 'include',
}
});
const link = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink,
);
2020-07-16 20:21:58 +02:00
const defaultOptions: DefaultOptions = {
watchQuery: {
fetchPolicy: 'no-cache',
errorPolicy: 'ignore',
},
query: {
fetchPolicy: 'no-cache',
errorPolicy: 'all',
},
};
this.gql = new ApolloClient<any>({
link: link,
cache: new InMemoryCache(),
2020-07-16 20:21:58 +02:00
defaultOptions,
});
2020-06-15 18:10:06 +02:00
}
fetchProfile() {
return this.gql.query({
query: gql`
query {
userProfile {
2020-07-16 20:21:58 +02:00
name,
email,
createdAt,
connectedAt
}
}`
})
.then(this.assertAuthorization)
2020-06-15 18:10:06 +02:00
}
2020-07-16 20:21:58 +02:00
updateProfile(changes: ProfileChanges) {
return this.gql.mutate({
variables: {
changes,
},
mutation: gql`
mutation updateProfile($changes: ProfileChanges!) {
updateProfile(changes: $changes) {
name,
email,
createdAt,
connectedAt
}
}`,
})
.then(this.assertAuthorization)
}
assertAuthorization({ status, data }: any) {
if (status === 401) return Promise.reject(new UnauthorizedError());
return data;
}
2020-06-15 18:10:06 +02:00
}