api.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. const config = require('../figma-import.config')
  2. const api = require('axios')
  3. const headers = {
  4. 'X-FIGMA-TOKEN': config.FIGMA_TOKEN,
  5. }
  6. /**
  7. * api endpoint for files
  8. *
  9. */
  10. const instanceFiles = api.create({
  11. baseURL: `https://api.figma.com/v1/files/${config.FILE_KEY}`,
  12. headers,
  13. })
  14. /**
  15. * api endpoint for images
  16. *
  17. */
  18. const instanceImages = api.create({
  19. baseURL: `https://api.figma.com/v1/images/${config.FILE_KEY}`,
  20. headers,
  21. })
  22. /**
  23. * get Figma document info
  24. *
  25. * @return {Promise<Object>}
  26. */
  27. const getDocument = async () => instanceFiles.get('/')
  28. /**
  29. * get Figma node info
  30. *
  31. * @param {string} nodeId
  32. * @return {Promise<Object>}
  33. */
  34. const getNode = async (nodeId) => instanceFiles.get(`/nodes?ids=${decodeURIComponent(nodeId)}`)
  35. /**
  36. * get Figma node children
  37. *
  38. * @param {string} nodeId
  39. * @return {Promise<[Object]>}
  40. */
  41. const getNodeChildren = async (nodeId) => {
  42. try {
  43. const {
  44. data: { nodes },
  45. } = await instanceFiles.get(`/nodes?ids=${decodeURIComponent(nodeId)}`)
  46. return nodes[nodeId].document.children
  47. } catch (e) {
  48. console.error(`Failed to get node children for node ID: "${nodeId}"`)
  49. console.error(e?.response?.data)
  50. return null
  51. }
  52. }
  53. /**
  54. * get Svg image resource url
  55. *
  56. * @param {string} nodeId
  57. * @return {Promise<string>}
  58. */
  59. const getSvgImageUrl = async (nodeId) => {
  60. const {
  61. data: { images },
  62. } = await instanceImages.get(`/?ids=${decodeURIComponent(nodeId)}&format=svg`)
  63. return images[nodeId]
  64. }
  65. /**
  66. * get image content
  67. *
  68. * @param {string} url - image url
  69. * @return {Promise<Object>}
  70. */
  71. const getImageContent = async (url) => api.get(url)
  72. module.exports = {
  73. getDocument,
  74. getNode,
  75. getNodeChildren,
  76. getSvgImageUrl,
  77. getImageContent,
  78. }