2021-11-18 18:16:44 +00:00
|
|
|
import { FastifyInstance } from 'fastify'
|
2021-11-27 22:37:58 +00:00
|
|
|
|
2021-11-16 10:20:33 +00:00
|
|
|
import { Config, StorageType } from '../config'
|
2021-11-27 22:37:58 +00:00
|
|
|
import { GCS } from './gcs'
|
2021-11-16 10:20:33 +00:00
|
|
|
import { Local } from './local'
|
2021-11-18 18:16:44 +00:00
|
|
|
import { Minio } from './minio'
|
2021-11-16 10:20:33 +00:00
|
|
|
|
2021-11-17 15:20:50 +00:00
|
|
|
export abstract class Storage {
|
2021-11-18 18:16:44 +00:00
|
|
|
abstract init(): Promise<void>
|
|
|
|
|
2021-11-17 15:20:50 +00:00
|
|
|
abstract readStream(path: string): Promise<NodeJS.ReadableStream>
|
|
|
|
abstract writeStream(path: string): Promise<NodeJS.WritableStream>
|
|
|
|
|
2021-11-18 18:16:44 +00:00
|
|
|
// list(path: string): Promise<string[]>
|
|
|
|
abstract exists(path: string): Promise<boolean>
|
|
|
|
abstract delete(path: string): Promise<void>
|
2021-11-16 10:20:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export let storage: Storage
|
|
|
|
|
2021-11-18 18:16:44 +00:00
|
|
|
export async function init(App: FastifyInstance) {
|
2021-11-16 10:20:33 +00:00
|
|
|
if (!storage) {
|
|
|
|
switch (Config.storage) {
|
|
|
|
case StorageType.Local:
|
2021-11-17 16:25:54 +00:00
|
|
|
storage = new Local(Config.localAssets)
|
2021-11-16 10:20:33 +00:00
|
|
|
break
|
2021-11-18 18:16:44 +00:00
|
|
|
case StorageType.S3:
|
|
|
|
storage = new Minio({
|
|
|
|
accessKey: Config.s3.accessKey,
|
|
|
|
secretKey: Config.s3.secretKey,
|
|
|
|
bucket: Config.s3.bucket,
|
|
|
|
region: Config.s3.region,
|
|
|
|
endpoint: 'https://s3.amazonaws.com',
|
|
|
|
})
|
|
|
|
break
|
|
|
|
case StorageType.Minio:
|
|
|
|
storage = new Minio({
|
|
|
|
accessKey: Config.minio.accessKey,
|
|
|
|
secretKey: Config.minio.secretKey,
|
|
|
|
endpoint: Config.minio.endpoint,
|
|
|
|
region: Config.minio.region,
|
|
|
|
bucket: Config.minio.bucket,
|
|
|
|
})
|
|
|
|
break
|
2021-11-27 22:37:58 +00:00
|
|
|
case StorageType.GCS:
|
|
|
|
storage = new GCS({
|
|
|
|
bucket: Config.gcs.bucket,
|
|
|
|
keyFilename: Config.gcs.keyFilename,
|
|
|
|
})
|
|
|
|
break
|
2021-11-16 10:20:33 +00:00
|
|
|
default:
|
|
|
|
throw new Error(`Unknown storage type: ${Config.storage}`)
|
|
|
|
}
|
2021-11-18 18:16:44 +00:00
|
|
|
try {
|
|
|
|
await storage.init()
|
|
|
|
App.log.debug(`Storage initialized: ${Config.storage}`)
|
|
|
|
} catch (e) {
|
2021-11-27 22:37:58 +00:00
|
|
|
App.log.error((e as Error).message)
|
2021-11-18 18:16:44 +00:00
|
|
|
App.log.error(`Storage initialization failed: ${Config.storage}`)
|
|
|
|
process.exit(1)
|
|
|
|
}
|
2021-11-16 10:20:33 +00:00
|
|
|
}
|
|
|
|
}
|