|
| 1 | +import { FsClient, HttpClient, FsClients, HttpClients } from '../../src' |
| 2 | +import { join } from '../../src/utils/join' |
| 3 | + |
| 4 | +const isBrowser = () => typeof window !== `undefined` |
| 5 | + |
| 6 | +const corsProxyUrlTransformer = (originalUrl: string) => { |
| 7 | + return `https://www.noteshub.app/api/cors-proxy.ts?url=${encodeURIComponent(originalUrl)}` |
| 8 | +} |
| 9 | + |
| 10 | +type IntegrationContext = { |
| 11 | + fs: FsClient |
| 12 | + http: HttpClient |
| 13 | + dir: string |
| 14 | +} |
| 15 | + |
| 16 | +export async function integrationContext(action: (context: IntegrationContext) => Promise<void>) { |
| 17 | + const { fs, http } = isBrowser() ? { |
| 18 | + fs: new FsClients.InMemoryFsClient(), |
| 19 | + http: HttpClients.makeWebHttpClient({ transformRequestUrl: corsProxyUrlTransformer }) |
| 20 | + } : { |
| 21 | + fs: (await import('fs')).promises, |
| 22 | + http: HttpClients.makeNodeHttpClient() |
| 23 | + } |
| 24 | + |
| 25 | + const dir = generateId(20) |
| 26 | + await fs.mkdir(dir) |
| 27 | + |
| 28 | + try { |
| 29 | + await action({ fs, http, dir }) |
| 30 | + } finally { |
| 31 | + await deleteRecursively(fs, dir) |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +function generateId(length: number) { |
| 36 | + let result = '' |
| 37 | + const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' |
| 38 | + const charactersLength = characters.length |
| 39 | + for (let i = 0; i < length; i++) { |
| 40 | + result += characters.charAt(Math.floor(Math.random() * charactersLength)) |
| 41 | + } |
| 42 | + return result |
| 43 | +} |
| 44 | + |
| 45 | +async function deleteRecursively(fs: FsClient, dirname: string) { |
| 46 | + const filesToDelete: string[] = [] |
| 47 | + const directoriesToDelete: string[] = [] |
| 48 | + const pathsToTraverse = [dirname] |
| 49 | + |
| 50 | + while (pathsToTraverse.length > 0) { |
| 51 | + const path = pathsToTraverse.pop()! |
| 52 | + |
| 53 | + if ((await fs.stat(path)).isDirectory()) { |
| 54 | + directoriesToDelete.push(path) |
| 55 | + pathsToTraverse.push( |
| 56 | + ...(await fs.readdir(path))!.map(subPath => join(path, subPath)) |
| 57 | + ) |
| 58 | + } else { |
| 59 | + filesToDelete.push(path) |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + for (const path of filesToDelete) { |
| 64 | + await fs.unlink(path) |
| 65 | + } |
| 66 | + for (const path of directoriesToDelete.reverse()) { |
| 67 | + await fs.rmdir(path) |
| 68 | + } |
| 69 | +} |
0 commit comments