-
Notifications
You must be signed in to change notification settings - Fork 71
/
static.effects.ts
57 lines (51 loc) · 1.54 KB
/
static.effects.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
import * as fs from 'fs';
import * as path from 'path';
import { r, combineRoutes, use } from '@marblejs/core';
import { requestValidator$, t } from '@marblejs/middleware-io';
import { multipart$ } from '@marblejs/middleware-multipart';
import { streamFileTo } from '@marblejs/middleware-multipart/dist/multipart.util';
import { readFile } from '@marblejs/core/dist/+internal';
import { map, mergeMap } from 'rxjs/operators';
const STATIC_PATH = path.resolve(__dirname, '../../../../assets');
const TMP_PATH = path.resolve(__dirname, '../../../../tmp');
const getFileValidator$ = requestValidator$({
params: t.type({ dir: t.string })
});
const postFile$ = r.pipe(
r.matchPath('/upload'),
r.matchType('POST'),
r.useEffect(req$ => req$.pipe(
use(multipart$({
files: ['image_1'],
stream: streamFileTo(TMP_PATH),
})),
map(req => ({
body: {
file: req.files,
body: req.body,
},
}))
)));
const getFileStream$ = r.pipe(
r.matchPath('/stream/:dir*'),
r.matchType('GET'),
r.useEffect(req$ => req$.pipe(
use(getFileValidator$),
map(req => req.params.dir),
map(dir => fs.createReadStream(path.resolve(STATIC_PATH, dir))),
map(body => ({ body })),
)),
);
const getFile$ = r.pipe(
r.matchPath('/:dir*'),
r.matchType('GET'),
r.useEffect(req$ => req$.pipe(
use(getFileValidator$),
map(req => req.params.dir),
mergeMap(readFile(STATIC_PATH)),
map(body => ({ body }))
)));
export const static$ = combineRoutes(
'/static',
[ postFile$, getFileStream$, getFile$ ],
);