blog/lib/rx-utils.ts

48 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-06-27 04:22:58 +00:00
import { from, mergeMap, Observable, Subscriber } from "rxjs";
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-27 08:06:39 +00:00
import { VFile } from "vfile";
import { read } from "to-vfile";
2024-06-26 02:21:31 +00:00
2024-06-26 03:30:43 +00:00
export function dest(prefix: string) {
2024-06-27 08:06:39 +00:00
return async (file: VFile) => {
2024-06-26 03:30:43 +00:00
const actualPath = join(prefix, file.path);
if (!existsSync(dirname(actualPath))) {
await mkdir(dirname(actualPath), { recursive: true });
}
2024-06-27 08:06:39 +00:00
await writeFile(actualPath, file.value);
2024-06-26 03:30:43 +00:00
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 08:06:39 +00:00
const loadFile = (path: string): Promise<VFile> =>
read(join(Deno.cwd(), path)).then((vfile) => {
vfile.path = path;
return vfile;
});
2024-06-27 01:36:05 +00:00
2024-06-27 08:06:39 +00:00
export const fromGlob = (paths: string | string[]): Observable<VFile> =>
2024-06-27 01:36:05 +00:00
from(new Glob(paths, {})).pipe(mergeMap(loadFile));