-
Notifications
You must be signed in to change notification settings - Fork 2k
/
customprovider.js
122 lines (104 loc) · 2.86 KB
/
customprovider.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
const request = require('request')
const BASE_URL = 'https://api.unsplash.com'
function adaptData (res) {
const data = {
username: null,
items: [],
nextPagePath: null,
}
const items = res
items.forEach((item) => {
const isFolder = !!item.published_at
data.items.push({
isFolder,
icon: isFolder ? item.cover_photo.urls.thumb : item.urls.thumb,
name: item.title || item.description,
mimeType: isFolder ? null : 'image/jpeg',
id: item.id,
thumbnail: isFolder ? item.cover_photo.urls.thumb : item.urls.thumb,
requestPath: item.id,
modifiedDate: item.updated_at,
size: null,
})
})
return data
}
/**
* an example of a custom provider module. It implements @uppy/companion's Provider interface
*/
class MyCustomProvider {
static version = 2
constructor () {
this.authProvider = 'myunsplash'
}
// eslint-disable-next-line class-methods-use-this
async list ({ token, directory }) {
const path = directory ? `/${directory}/photos` : ''
const options = {
url: `${BASE_URL}/collections${path}`,
method: 'GET',
json: true,
headers: {
Authorization: `Bearer ${token}`,
},
}
return new Promise((resolve, reject) => (
request(options, (err, resp, body) => {
if (err) {
console.log(err)
reject(err)
return
}
resolve(adaptData(body))
})))
}
// eslint-disable-next-line class-methods-use-this
async download ({ id, token }) {
const options = {
url: `${BASE_URL}/photos/${id}`,
method: 'GET',
json: true,
headers: {
Authorization: `Bearer ${token}`,
},
}
const resp = await new Promise((resolve, reject) => {
const req = request(options)
.on('response', (response) => {
// Don't allow any more data to flow yet.
// https://github.com/request/request/issues/1990#issuecomment-184712275
response.pause()
if (resp.statusCode !== 200) {
req.abort() // Or we will leak memory
reject(new Error(`HTTP response ${resp.statusCode}`))
return
}
resolve(response)
})
.on('error', reject)
})
// The returned stream will be consumed and uploaded from the current position
return { stream: resp }
}
// eslint-disable-next-line class-methods-use-this
async size ({ id, token }) {
const options = {
url: `${BASE_URL}/photos/${id}`,
method: 'GET',
json: true,
headers: {
Authorization: `Bearer ${token}`,
},
}
return new Promise((resolve, reject) => (
request(options, (err, resp, body) => {
if (err) {
console.log(err)
reject(err)
return
}
resolve(body.size)
})))
}
}
module.exports = MyCustomProvider