]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/extra-utils/mock-servers/mock-object-storage.ts
Optimize torrent URL update
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / mock-servers / mock-object-storage.ts
1 import * as express from 'express'
2 import got, { RequestError } from 'got'
3 import { Server } from 'http'
4 import { pipeline } from 'stream'
5 import { randomInt } from '@shared/core-utils'
6 import { ObjectStorageCommand } from '../server'
7
8 export class MockObjectStorage {
9 private server: Server
10
11 initialize () {
12 return new Promise<number>(res => {
13 const app = express()
14
15 app.get('/:bucketName/:path(*)', (req: express.Request, res: express.Response, next: express.NextFunction) => {
16 const url = `http://${req.params.bucketName}.${ObjectStorageCommand.getEndpointHost()}/${req.params.path}`
17
18 if (process.env.DEBUG) {
19 console.log('Receiving request on mocked server %s.', req.url)
20 console.log('Proxifying request to %s', url)
21 }
22
23 return pipeline(
24 got.stream(url, { throwHttpErrors: false }),
25 res,
26 (err: RequestError) => {
27 if (!err) return
28
29 console.error('Pipeline failed.', err)
30 }
31 )
32 })
33
34 const port = 42301 + randomInt(1, 100)
35 this.server = app.listen(port, () => res(port))
36 })
37 }
38
39 terminate () {
40 if (this.server) this.server.close()
41 }
42 }