CustomProvider.cjs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. const { Readable } = require('node:stream')
  2. const BASE_URL = 'https://api.unsplash.com'
  3. function adaptData (res) {
  4. const data = {
  5. username: null,
  6. items: [],
  7. nextPagePath: null,
  8. }
  9. const items = res
  10. items.forEach((item) => {
  11. const isFolder = !!item.published_at
  12. data.items.push({
  13. isFolder,
  14. icon: isFolder ? item.cover_photo.urls.thumb : item.urls.thumb,
  15. name: item.title || item.description,
  16. mimeType: isFolder ? null : 'image/jpeg',
  17. id: item.id,
  18. thumbnail: isFolder ? item.cover_photo.urls.thumb : item.urls.thumb,
  19. requestPath: item.id,
  20. modifiedDate: item.updated_at,
  21. size: null,
  22. })
  23. })
  24. return data
  25. }
  26. /**
  27. * an example of a custom provider module. It implements @uppy/companion's Provider interface
  28. */
  29. class MyCustomProvider {
  30. static version = 2
  31. authProvider = 'myunsplash'
  32. // eslint-disable-next-line class-methods-use-this
  33. async list ({ token, directory }) {
  34. const path = directory ? `/${directory}/photos` : ''
  35. const resp = await fetch(`${BASE_URL}/collections${path}`, {
  36. headers:{
  37. Authorization: `Bearer ${token}`,
  38. },
  39. })
  40. if (!resp.ok) {
  41. throw new Error(`Errornous HTTP response (${resp.status} ${resp.statusText})`)
  42. }
  43. return adaptData(await resp.json())
  44. }
  45. // eslint-disable-next-line class-methods-use-this
  46. async download ({ id, token }) {
  47. const resp = await fetch(`${BASE_URL}/photos/${id}`, {
  48. headers: {
  49. Authorization: `Bearer ${token}`,
  50. },
  51. })
  52. if (!resp.ok) {
  53. throw new Error(`Errornous HTTP response (${resp.status} ${resp.statusText})`)
  54. }
  55. return { stream: Readable.fromWeb(resp.body) }
  56. }
  57. // eslint-disable-next-line class-methods-use-this
  58. async size ({ id, token }) {
  59. const resp = await fetch(`${BASE_URL}/photos/${id}`, {
  60. headers: {
  61. Authorization: `Bearer ${token}`,
  62. },
  63. })
  64. if (!resp.ok) {
  65. throw new Error(`Errornous HTTP response (${resp.status} ${resp.statusText})`)
  66. }
  67. const { size } = await resp.json()
  68. return size
  69. }
  70. }
  71. module.exports = MyCustomProvider