api.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import axios from 'axios'
  2. import { print } from 'graphql/language/printer'
  3. import { Node, Nodes, AllNodesOfVariant, NodesTrees } from '@/api/queries'
  4. import * as nodesFragments from '@/api/fragments'
  5. const api = axios.create({
  6. baseURL: window.location.origin + '/api/gql',
  7. headers: {
  8. Accept: 'application/json',
  9. 'Content-Type': 'application/json'
  10. }
  11. })
  12. export default {
  13. getQueryString (query, levels) {
  14. const FRAGMENTS_NAMES = ['NodeInitial', 'NodePartial', 'NodeFull']
  15. const names = levels.map(level => FRAGMENTS_NAMES[level])
  16. const fragments = names.map(name => '...' + name).join('\n')
  17. const fragmentsDefs = names.map(name => print(nodesFragments[name])).join('\n')
  18. return print(query).replace('FRAGMENTS', fragments) + fragmentsDefs
  19. },
  20. query (query, variables = {}) {
  21. return api
  22. .post('', { query: print(query), variables })
  23. .then(response => {
  24. return response.data.data
  25. })
  26. },
  27. queryNodes (ids, levels) {
  28. return api.post('', {
  29. query: this.getQueryString(Nodes, levels),
  30. variables: { ids }
  31. }).then(response => response.data.data)
  32. },
  33. queryNode (id, levels) {
  34. return api.post('', {
  35. query: this.getQueryString(Node, levels),
  36. variables: { id }
  37. }).then(response => response.data.data)
  38. },
  39. queryAllNodes (variantId, levels) {
  40. return api.post('', {
  41. query: this.getQueryString(AllNodesOfVariant, levels),
  42. variables: { variantId }
  43. }).then(response => response.data.data)
  44. },
  45. queryRecursiveNodes (ids, depth = 4) {
  46. const baseQuery = print(NodesTrees)
  47. const prodFragment = `
  48. ... on Textprod {
  49. #parents: text_de_depart {
  50. # id
  51. #}
  52. siblings: text_en_rebond {
  53. id
  54. FRAGMENT_REF
  55. }
  56. }
  57. `
  58. const refFragment = `
  59. ... on Textref {
  60. siblings: text_en_rebond {
  61. id
  62. FRAGMENT_REF
  63. }
  64. children: text_produits {
  65. id
  66. FRAGMENT_PROD
  67. }
  68. creations: field_creations {
  69. id
  70. siblings: rebonds {
  71. id
  72. }
  73. }
  74. }
  75. `
  76. function formatFragment (str, depth) {
  77. if (depth > 0) {
  78. return formatFragment(
  79. str.replaceAll('FRAGMENT_REF', refFragment).replaceAll('FRAGMENT_PROD', prodFragment),
  80. --depth
  81. )
  82. } else {
  83. return str.replaceAll('FRAGMENT_REF', '').replaceAll('FRAGMENT_PROD', '')
  84. }
  85. }
  86. return api.post('', {
  87. query: baseQuery.replace('FRAGMENT', formatFragment(refFragment + prodFragment, depth)),
  88. variables: { id: ids[0] }
  89. }).then(response => response.data.data.node)
  90. }
  91. }