hostAdminClient.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. const hostAdminURL = Cypress.env('HOST_ADMIN_URL') || 'http://host-admin'
  2. export async function dockerCompose(cmd: string, ...args: string[]) {
  3. return await fetchJSON(`${hostAdminURL}/docker/compose/${cmd}`, {
  4. method: 'POST',
  5. body: JSON.stringify({
  6. args,
  7. }),
  8. })
  9. }
  10. export async function reconfigure({
  11. pro = false,
  12. version = 'latest',
  13. vars = {},
  14. withDataDir = false,
  15. resetData = false,
  16. }): Promise<{ previousConfigServer: string }> {
  17. return await fetchJSON(`${hostAdminURL}/reconfigure`, {
  18. method: 'POST',
  19. body: JSON.stringify({
  20. pro,
  21. version,
  22. vars,
  23. withDataDir,
  24. resetData,
  25. }),
  26. })
  27. }
  28. async function fetchJSON<T = { stdout: string; stderr: string }>(
  29. input: RequestInfo,
  30. init?: RequestInit
  31. ): Promise<T> {
  32. if (init?.body) {
  33. init.headers = { 'Content-Type': 'application/json' }
  34. }
  35. let res
  36. for (let attempt = 0; attempt < 5; attempt++) {
  37. try {
  38. res = await fetch(input, init)
  39. break
  40. } catch {
  41. await sleep(3_000)
  42. }
  43. }
  44. if (!res) {
  45. res = await fetch(input, init)
  46. }
  47. const { error, stdout, stderr, ...rest } = await res.json()
  48. if (error) {
  49. console.error(input, init, 'failed:', error)
  50. if (stdout) console.log(stdout)
  51. if (stderr) console.warn(stderr)
  52. const err = new Error(error.message)
  53. Object.assign(err, error)
  54. throw err
  55. }
  56. return { stdout, stderr, ...rest }
  57. }
  58. export async function runScript({
  59. cwd,
  60. script,
  61. args = [],
  62. }: {
  63. cwd: string
  64. script: string
  65. args?: string[]
  66. }) {
  67. return await fetchJSON(`${hostAdminURL}/run/script`, {
  68. method: 'POST',
  69. body: JSON.stringify({
  70. cwd,
  71. script,
  72. args,
  73. }),
  74. })
  75. }
  76. export async function getRedisKeys() {
  77. const { stdout } = await fetchJSON(`${hostAdminURL}/redis/keys`, {
  78. method: 'GET',
  79. })
  80. return stdout.split('\n')
  81. }
  82. async function sleep(ms: number) {
  83. return new Promise(resolve => {
  84. setTimeout(resolve, ms)
  85. })
  86. }