-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathplugins.module.ts
More file actions
93 lines (85 loc) · 2.69 KB
/
plugins.module.ts
File metadata and controls
93 lines (85 loc) · 2.69 KB
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
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import fs from 'node:fs'
import fsPromises from 'node:fs/promises'
import path from 'node:path'
import { Writable } from 'node:stream'
import { fileURLToPath } from 'node:url'
import {
ApolloPlugin,
type ApolloPluginConstructor,
} from '@apollo-annotation/common'
import {
type DynamicModule,
Logger,
Module,
type Provider,
} from '@nestjs/common'
import sanitize from 'sanitize-filename'
import { APOLLO_PLUGINS } from './plugins.constants.js'
import { PluginsService } from './plugins.service.js'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
@Module({})
export class PluginsModule {
private readonly logger = new Logger(PluginsModule.name)
static async registerAsync(): Promise<DynamicModule> {
const { PLUGIN_URLS, PLUGIN_URLS_FILE } = process.env
let pluginURLs = PLUGIN_URLS ? PLUGIN_URLS.split(',') : []
if (pluginURLs.length === 0 && PLUGIN_URLS_FILE) {
const pluginURLsFileText = await fsPromises.readFile(
PLUGIN_URLS_FILE,
'utf8',
)
pluginURLs = pluginURLsFileText
.split(/\n|\r\n|\r/)
.map((line) => line.trim())
}
const pluginsProvider: Provider = {
provide: APOLLO_PLUGINS,
useFactory: () => PluginsModule.fetchPlugins(pluginURLs),
}
return {
module: PluginsModule,
global: true,
providers: [pluginsProvider, PluginsService],
exports: [pluginsProvider, PluginsService],
}
}
static async fetchPlugins(urls: string[]) {
const plugins: ApolloPlugin[] = []
for (const url of urls) {
const tmpDir = await fsPromises.mkdtemp(
path.join(__dirname, 'jbrowse-plugin-'),
)
let plugin: { default: ApolloPluginConstructor } | undefined
try {
const pluginLocation = path.join(tmpDir, sanitize(url))
const pluginLocationRelative = `.${path.sep}${path.relative(
__dirname,
pluginLocation,
)}`
const file = Writable.toWeb(fs.createWriteStream(pluginLocation))
const response = await fetch(url)
if (!response.body) {
throw new Error('fetch failed')
}
try {
await response.body.pipeTo(file)
} catch (error) {
fs.unlinkSync(pluginLocation)
console.error(error)
throw error
}
plugin = await import(pluginLocationRelative)
} finally {
await fsPromises.rm(tmpDir, { recursive: true })
}
if (!plugin) {
throw new Error(`Could not load plugin: ${url}`)
}
const PluginClass = plugin.default
const runtimePlugin = new PluginClass()
plugins.push(runtimePlugin)
}
return plugins
}
}