upload.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import Path from 'path'
  2. import { promises as fs } from 'fs'
  3. import { promisify } from 'util'
  4. import oneSky from '@brainly/onesky-utils'
  5. import Config from './config.js'
  6. import { fileURLToPath } from 'url'
  7. const __dirname = fileURLToPath(new URL('.', import.meta.url))
  8. const { withAuth } = Config
  9. const sleep = promisify(setTimeout)
  10. async function uploadLocales() {
  11. // Docs: https://github.com/onesky/api-documentation-platform/blob/master/resources/file.md#upload---upload-a-file
  12. const blob = await oneSky.postFile(
  13. withAuth({
  14. fileName: 'en-US.json',
  15. language: 'en-GB',
  16. format: 'HIERARCHICAL_JSON',
  17. content: await fs.readFile(
  18. Path.join(__dirname, '/../../locales/en.json')
  19. ),
  20. keepStrings: false, // deprecate locales that no longer exist in en.json
  21. })
  22. )
  23. return JSON.parse(blob).data.import.id
  24. }
  25. async function getImportTask(importId) {
  26. // Docs: https://github.com/onesky/api-documentation-platform/blob/master/resources/import_task.md
  27. const blob = await oneSky.getImportTask(withAuth({ importId }))
  28. return JSON.parse(blob).data
  29. }
  30. async function pollUploadStatus(importId) {
  31. let task
  32. while ((task = await getImportTask(importId)).status === 'in-progress') {
  33. console.log('onesky is processing the import ...')
  34. await sleep(5000)
  35. }
  36. if (task.status === 'failed') {
  37. console.error(JSON.stringify({ task }, null, 2))
  38. throw new Error('upload failed')
  39. }
  40. }
  41. async function uploadOnce() {
  42. const importId = await uploadLocales()
  43. await pollUploadStatus(importId)
  44. }
  45. async function main() {
  46. try {
  47. await uploadOnce()
  48. } catch (err) {
  49. console.error('--- upload failed once ---')
  50. console.error(err)
  51. console.error('--- upload failed once ---')
  52. console.log('retrying upload in 30s')
  53. await sleep(30_000)
  54. await uploadOnce()
  55. }
  56. }
  57. try {
  58. await main()
  59. } catch (error) {
  60. console.error({ error })
  61. process.exit(1)
  62. }