You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

80 line
1.7 KiB

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