]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/server-commands/requests/requests.ts
Add ability to customize token lifetime
[github/Chocobozzz/PeerTube.git] / shared / server-commands / requests / requests.ts
1 /* eslint-disable @typescript-eslint/no-floating-promises */
2
3 import { decode } from 'querystring'
4 import request from 'supertest'
5 import { URL } from 'url'
6 import { buildAbsoluteFixturePath, pick } from '@shared/core-utils'
7 import { HttpStatusCode } from '@shared/models'
8
9 export type CommonRequestParams = {
10 url: string
11 path?: string
12 contentType?: string
13 range?: string
14 redirects?: number
15 accept?: string
16 host?: string
17 token?: string
18 headers?: { [ name: string ]: string }
19 type?: string
20 xForwardedFor?: string
21 expectedStatus?: HttpStatusCode
22 }
23
24 function makeRawRequest (options: {
25 url: string
26 token?: string
27 expectedStatus?: HttpStatusCode
28 range?: string
29 query?: { [ id: string ]: string }
30 }) {
31 const { host, protocol, pathname } = new URL(options.url)
32
33 return makeGetRequest({
34 url: `${protocol}//${host}`,
35 path: pathname,
36 contentType: undefined,
37
38 ...pick(options, [ 'expectedStatus', 'range', 'token', 'query' ])
39 })
40 }
41
42 function makeGetRequest (options: CommonRequestParams & {
43 query?: any
44 rawQuery?: string
45 }) {
46 const req = request(options.url).get(options.path)
47
48 if (options.query) req.query(options.query)
49 if (options.rawQuery) req.query(options.rawQuery)
50
51 return buildRequest(req, { contentType: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
52 }
53
54 function makeHTMLRequest (url: string, path: string) {
55 return makeGetRequest({
56 url,
57 path,
58 accept: 'text/html',
59 expectedStatus: HttpStatusCode.OK_200
60 })
61 }
62
63 function makeActivityPubGetRequest (url: string, path: string, expectedStatus = HttpStatusCode.OK_200) {
64 return makeGetRequest({
65 url,
66 path,
67 expectedStatus,
68 accept: 'application/activity+json,text/html;q=0.9,\\*/\\*;q=0.8'
69 })
70 }
71
72 function makeDeleteRequest (options: CommonRequestParams & {
73 query?: any
74 rawQuery?: string
75 }) {
76 const req = request(options.url).delete(options.path)
77
78 if (options.query) req.query(options.query)
79 if (options.rawQuery) req.query(options.rawQuery)
80
81 return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
82 }
83
84 function makeUploadRequest (options: CommonRequestParams & {
85 method?: 'POST' | 'PUT'
86
87 fields: { [ fieldName: string ]: any }
88 attaches?: { [ attachName: string ]: any | any[] }
89 }) {
90 let req = options.method === 'PUT'
91 ? request(options.url).put(options.path)
92 : request(options.url).post(options.path)
93
94 req = buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
95
96 buildFields(req, options.fields)
97
98 Object.keys(options.attaches || {}).forEach(attach => {
99 const value = options.attaches[attach]
100 if (!value) return
101
102 if (Array.isArray(value)) {
103 req.attach(attach, buildAbsoluteFixturePath(value[0]), value[1])
104 } else {
105 req.attach(attach, buildAbsoluteFixturePath(value))
106 }
107 })
108
109 return req
110 }
111
112 function makePostBodyRequest (options: CommonRequestParams & {
113 fields?: { [ fieldName: string ]: any }
114 }) {
115 const req = request(options.url).post(options.path)
116 .send(options.fields)
117
118 return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
119 }
120
121 function makePutBodyRequest (options: {
122 url: string
123 path: string
124 token?: string
125 fields: { [ fieldName: string ]: any }
126 expectedStatus?: HttpStatusCode
127 }) {
128 const req = request(options.url).put(options.path)
129 .send(options.fields)
130
131 return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
132 }
133
134 function decodeQueryString (path: string) {
135 return decode(path.split('?')[1])
136 }
137
138 function unwrapBody <T> (test: request.Test): Promise<T> {
139 return test.then(res => res.body)
140 }
141
142 function unwrapText (test: request.Test): Promise<string> {
143 return test.then(res => res.text)
144 }
145
146 function unwrapBodyOrDecodeToJSON <T> (test: request.Test): Promise<T> {
147 return test.then(res => {
148 if (res.body instanceof Buffer) {
149 try {
150 return JSON.parse(new TextDecoder().decode(res.body))
151 } catch (err) {
152 console.error('Cannot decode JSON.', res.body)
153 throw err
154 }
155 }
156
157 return res.body
158 })
159 }
160
161 function unwrapTextOrDecode (test: request.Test): Promise<string> {
162 return test.then(res => res.text || new TextDecoder().decode(res.body))
163 }
164
165 // ---------------------------------------------------------------------------
166
167 export {
168 makeHTMLRequest,
169 makeGetRequest,
170 decodeQueryString,
171 makeUploadRequest,
172 makePostBodyRequest,
173 makePutBodyRequest,
174 makeDeleteRequest,
175 makeRawRequest,
176 makeActivityPubGetRequest,
177 unwrapBody,
178 unwrapTextOrDecode,
179 unwrapBodyOrDecodeToJSON,
180 unwrapText
181 }
182
183 // ---------------------------------------------------------------------------
184
185 function buildRequest (req: request.Test, options: CommonRequestParams) {
186 if (options.contentType) req.set('Accept', options.contentType)
187 if (options.token) req.set('Authorization', 'Bearer ' + options.token)
188 if (options.range) req.set('Range', options.range)
189 if (options.accept) req.set('Accept', options.accept)
190 if (options.host) req.set('Host', options.host)
191 if (options.redirects) req.redirects(options.redirects)
192 if (options.xForwardedFor) req.set('X-Forwarded-For', options.xForwardedFor)
193 if (options.type) req.type(options.type)
194
195 Object.keys(options.headers || {}).forEach(name => {
196 req.set(name, options.headers[name])
197 })
198
199 return req.expect((res) => {
200 if (options.expectedStatus && res.status !== options.expectedStatus) {
201 throw new Error(`Expected status ${options.expectedStatus}, got ${res.status}. ` +
202 `\nThe server responded: "${res.body?.error ?? res.text}".\n` +
203 'You may take a closer look at the logs. To see how to do so, check out this page: ' +
204 'https://github.com/Chocobozzz/PeerTube/blob/develop/support/doc/development/tests.md#debug-server-logs')
205 }
206 return res
207 })
208 }
209
210 function buildFields (req: request.Test, fields: { [ fieldName: string ]: any }, namespace?: string) {
211 if (!fields) return
212
213 let formKey: string
214
215 for (const key of Object.keys(fields)) {
216 if (namespace) formKey = `${namespace}[${key}]`
217 else formKey = key
218
219 if (fields[key] === undefined) continue
220
221 if (Array.isArray(fields[key]) && fields[key].length === 0) {
222 req.field(key, [])
223 continue
224 }
225
226 if (fields[key] !== null && typeof fields[key] === 'object') {
227 buildFields(req, fields[key], formKey)
228 } else {
229 req.field(formKey, fields[key])
230 }
231 }
232 }