This repository has been archived by the owner on Jul 9, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asset.ts
65 lines (55 loc) · 1.54 KB
/
asset.ts
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
import * as fs from 'fs';
import * as util from 'util';
import { Injectable } from '@travetto/di';
import { Asset, AssetMetadata } from '../model';
import { AssetSource } from './source';
const fsUnlinkAsync = util.promisify(fs.unlink);
@Injectable()
export class AssetService {
constructor(private source: AssetSource) { }
async remove(path: string) {
return await this.source.remove(path);
}
async save(asset: Asset, upsert = true, removeOnComplete = true) {
try {
let res: Asset | undefined;
try {
res = await this.source.info(asset.filename);
} catch (e) {
// Not found
}
if (res && !upsert) {
throw new Error(`File already exists: ${asset.filename}`);
} else {
return await this.source.write(asset, fs.createReadStream(asset.path));
}
} finally {
if (removeOnComplete) {
try {
await fsUnlinkAsync(asset.path);
} catch (e) {
// Do nothings
}
}
}
}
async saveAll(uploads: Asset[]) {
return await Promise.all(uploads.map(u => this.save(u)));
}
async get(filename: string, haveTags?: string[]): Promise<Asset> {
const info = await this.source.info(filename);
if (haveTags) {
const fin = new Set(info.metadata.tags);
for (const t of haveTags) {
if (!fin.has(t)) {
throw new Error();
}
}
}
if (info.metadata.title) {
info.filename = info.metadata.title;
}
info.stream = await this.source.read(filename);
return info;
}
}