CustomProvider.cjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. static get oauthProvider () {
  32. return 'myunsplash'
  33. }
  34. // eslint-disable-next-line class-methods-use-this
  35. async list ({ token, directory }) {
  36. const path = directory ? `/${directory}/photos` : ''
  37. const resp = await fetch(`${BASE_URL}/collections${path}`, {
  38. headers:{
  39. Authorization: `Bearer ${token}`,
  40. },
  41. })
  42. if (!resp.ok) {
  43. throw new Error(`Errornous HTTP response (${resp.status} ${resp.statusText})`)
  44. }
  45. return adaptData(await resp.json())
  46. }
  47. // eslint-disable-next-line class-methods-use-this
  48. async download ({ id, token }) {
  49. const resp = await fetch(`${BASE_URL}/photos/${id}`, {
  50. headers: {
  51. Authorization: `Bearer ${token}`,
  52. },
  53. })
  54. if (!resp.ok) {
  55. throw new Error(`Errornous HTTP response (${resp.status} ${resp.statusText})`)
  56. }
  57. return { stream: Readable.fromWeb(resp.body) }
  58. }
  59. // eslint-disable-next-line class-methods-use-this
  60. async size ({ id, token }) {
  61. const resp = await fetch(`${BASE_URL}/photos/${id}`, {
  62. headers: {
  63. Authorization: `Bearer ${token}`,
  64. },
  65. })
  66. if (!resp.ok) {
  67. throw new Error(`Errornous HTTP response (${resp.status} ${resp.statusText})`)
  68. }
  69. const { size } = await resp.json()
  70. return size
  71. }
  72. }
  73. module.exports = MyCustomProvider