api.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import axios from 'axios'
  2. import { print } from 'graphql/language/printer'
  3. import { Node, Nodes, 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. queryRecursiveNodes (ids, depth = 4) {
  40. const baseQuery = print(NodesTrees)
  41. const prodFragment = `
  42. ... on Textprod {
  43. parents: text_de_depart {
  44. id
  45. }
  46. siblings: text_en_rebond {
  47. id
  48. FRAGMENT_REF
  49. }
  50. }
  51. `
  52. const refFragment = `
  53. ... on Textref {
  54. siblings: text_en_rebond {
  55. id
  56. FRAGMENT_REF
  57. }
  58. children: text_produits {
  59. id
  60. FRAGMENT_PROD
  61. }
  62. creations: field_creations {
  63. id
  64. siblings: rebonds {
  65. id
  66. }
  67. }
  68. }
  69. `
  70. function formatFragment (str, depth) {
  71. if (depth > 0) {
  72. return formatFragment(
  73. str.replaceAll('FRAGMENT_REF', refFragment).replaceAll('FRAGMENT_PROD', prodFragment),
  74. --depth
  75. )
  76. } else {
  77. return str.replaceAll('FRAGMENT_REF', '').replaceAll('FRAGMENT_PROD', '')
  78. }
  79. }
  80. return api.post('', {
  81. query: baseQuery.replace('FRAGMENT', formatFragment(refFragment + prodFragment, depth)),
  82. variables: { id: ids[0] }
  83. }).then(response => response.data.data.node)
  84. }
  85. }