Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 

96 linhas
2.2 KiB

  1. import {
  2. ApolloClient,
  3. InMemoryCache,
  4. gql,
  5. ApolloLink,
  6. concat,
  7. // useQuery,
  8. // createHttpLink,
  9. HttpLink
  10. } from "@apollo/client";
  11. import ApolloConfig from "../config/apollo-config";
  12. // import fetch from "cross-fetch";
  13. function errorHandler(object) {
  14. return object.graphQLErrors.length != 0
  15. ? object.graphQLErrors[0].message
  16. : object.networkError && object.networkError.result
  17. ? object.networkError.result.errors.join(" ; ")
  18. : object.networkError
  19. ? object.networkError[Object.keys(object.networkError)[0]].toString()
  20. : "Fetch failed";
  21. }
  22. function initApollo(token) {
  23. // const httpLink = createHttpLink({
  24. // uri: ApolloConfig.graphql_uri,
  25. // fetch: fetch,
  26. // headers:
  27. // token != ""
  28. // ? {
  29. // Authorization: `Bearer ${token}`,
  30. // }
  31. // : null,
  32. // });
  33. const httpLink = new HttpLink({ uri: ApolloConfig.graphql_uri });
  34. const authMiddleware = new ApolloLink((operation, forward) => {
  35. operation.setContext(({ headers = {} }) => token == ""?headers:({
  36. headers: {
  37. ...headers,
  38. Authorization: `Bearer ${token}`,
  39. }
  40. }));
  41. return forward(operation);
  42. })
  43. return new ApolloClient({
  44. cache: new InMemoryCache({
  45. addTypename: false,
  46. }),
  47. link: concat(authMiddleware, httpLink),
  48. });
  49. }
  50. async function query(query, token = "", variables = {}, cache = false) {
  51. const client = initApollo(token);
  52. var res;
  53. try {
  54. var sql = await client.query({
  55. query: gql`
  56. ${query}
  57. `,
  58. variables: variables,
  59. fetchPolicy: cache ? "cache-first" : "no-cache",
  60. });
  61. res = { STATUS: 1, DATA: sql.data };
  62. } catch (e) {
  63. console.log(e.message);
  64. res = { STATUS: 0, DATA: e.message };
  65. }
  66. return res;
  67. }
  68. async function mutation(mutation, token = "", variables = {}) {
  69. const client = initApollo(token);
  70. var res;
  71. try {
  72. var sql = await client.mutate({
  73. mutation: gql`
  74. ${mutation}
  75. `,
  76. variables: variables,
  77. });
  78. res = { STATUS: 1, DATA: sql.data };
  79. } catch (e) {
  80. console.log(e.message);
  81. res = { STATUS: 0, DATA: e.message };
  82. }
  83. return res;
  84. }
  85. module.exports = {
  86. query: query,
  87. mutation: mutation,
  88. };