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.

69 lines
1.4 KiB

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