]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/tests/utils/miscs/miscs.ts
2147a07ff6387c9037c52188abdb15e642225b6d
[github/Chocobozzz/PeerTube.git] / server / tests / utils / miscs / miscs.ts
1 import * as WebTorrent from 'webtorrent'
2 import { readFile, readdir } from 'fs'
3
4 let webtorrent = new WebTorrent()
5
6 function immutableAssign <T, U> (target: T, source: U) {
7 return Object.assign<{}, T, U>({}, target, source)
8 }
9
10 function readFilePromise (path: string) {
11 return new Promise<Buffer>((res, rej) => {
12 readFile(path, (err, data) => {
13 if (err) return rej(err)
14
15 return res(data)
16 })
17 })
18 }
19
20 function readdirPromise (path: string) {
21 return new Promise<string[]>((res, rej) => {
22 readdir(path, (err, files) => {
23 if (err) return rej(err)
24
25 return res(files)
26 })
27 })
28 }
29
30 // Default interval -> 2 minutes
31 function dateIsValid (dateString: string, interval = 120000) {
32 const dateToCheck = new Date(dateString)
33 const now = new Date()
34
35 return Math.abs(now.getTime() - dateToCheck.getTime()) <= interval
36 }
37
38 function wait (milliseconds: number) {
39 return new Promise(resolve => setTimeout(resolve, milliseconds))
40 }
41
42 function webtorrentAdd (torrent: string, refreshWebTorrent = false) {
43 if (refreshWebTorrent === true) webtorrent = new WebTorrent()
44
45 return new Promise<WebTorrent.Torrent>(res => webtorrent.add(torrent, res))
46 }
47
48 // ---------------------------------------------------------------------------
49
50 export {
51 readFilePromise,
52 readdirPromise,
53 dateIsValid,
54 wait,
55 webtorrentAdd,
56 immutableAssign
57 }