blog/lib/rx-utils.ts

44 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-06-27 04:22:58 +00:00
import { from, mergeMap, Observable, Subscriber } from "rxjs";
2024-06-26 02:21:31 +00:00
import File from "vinyl";
import { readFile } from "node:fs/promises";
2024-06-27 04:22:58 +00:00
import { dirname, join } from "node:path";
2024-06-26 03:30:43 +00:00
import { existsSync } from "node:fs";
2024-06-27 04:22:58 +00:00
import { mkdir, writeFile } from "node:fs/promises";
2024-06-27 01:36:05 +00:00
import { Glob } from "glob";
2024-06-26 02:21:31 +00:00
2024-06-26 03:30:43 +00:00
export function dest(prefix: string) {
return async (file: File) => {
const actualPath = join(prefix, file.path);
if (!existsSync(dirname(actualPath))) {
await mkdir(dirname(actualPath), { recursive: true });
}
await writeFile(actualPath, file.contents as Buffer);
console.log("[-] Written", actualPath);
return file;
};
2024-06-26 02:38:13 +00:00
}
2024-06-27 01:28:17 +00:00
export function onComplete<T>(f: (sink: Subscriber<T>) => Promise<void>) {
return (observable: Observable<T>) =>
new Observable<T>((subscriber) =>
2024-06-26 02:21:31 +00:00
observable.subscribe({
next(value) {
2024-06-27 01:28:17 +00:00
subscriber.next(value);
},
error(err) {
subscriber.error(err);
2024-06-26 02:21:31 +00:00
},
complete() {
2024-06-27 01:28:17 +00:00
f(subscriber);
subscriber.complete();
2024-06-26 02:21:31 +00:00
},
2024-06-27 04:22:58 +00:00
})
2024-06-27 01:28:17 +00:00
);
2024-06-26 02:21:31 +00:00
}
2024-06-27 01:36:05 +00:00
2024-06-27 04:22:58 +00:00
const loadFile = async (path: string): Promise<File> => new File({ path, contents: await readFile(path) });
2024-06-27 01:36:05 +00:00
export const fromGlob = (paths: string | string[]): Observable<File> =>
from(new Glob(paths, {})).pipe(mergeMap(loadFile));