diff --git a/src/public/fs/json.ts b/src/public/fs/json.ts index 7189a3e..55d89cf 100644 --- a/src/public/fs/json.ts +++ b/src/public/fs/json.ts @@ -1,7 +1,7 @@ -import { IOfType } from '~/types'; import expose from '~/utils/expose'; import rw from './rw'; -import { IFsUpdateOptions, TContentFn, TSource } from './types'; +import { IFsUpdateOptions, TContentFn, TSource, TJsonFn } from './types'; +import { IOfType } from '~/types'; export default expose(json); @@ -12,15 +12,16 @@ export default expose(json); */ function json( file: TSource, - fn: ( - file: string, - json?: IOfType - ) => IOfType | void | Promise | void>, + fn: TJsonFn, options?: IFsUpdateOptions ): () => Promise { return async () => { - const _fn: TContentFn = async (file, raw) => { - const json = await fn(file, raw ? JSON.parse(raw) : undefined); + const _fn: TContentFn = async (data) => { + Object.defineProperty(data, 'json', { + enumerable: true, + get: (): IOfType => (data.raw ? JSON.parse(data.raw) : undefined) + }); + const json = await fn(data); return json ? JSON.stringify(json, null, 2) : undefined; }; diff --git a/src/public/fs/rw/rw.ts b/src/public/fs/rw/rw.ts index 0012c95..a18f795 100644 --- a/src/public/fs/rw/rw.ts +++ b/src/public/fs/rw/rw.ts @@ -26,14 +26,12 @@ export async function each( const cwd = process.cwd(); file = absolute({ path: file, cwd }); const relative = './' + path.relative(cwd, file); - const doesExist = await exists(file, { fail: options.fail }); - const raw = doesExist ? await fs.readFile(file).then(String) : undefined; let response: string | void; try { - response = await fn(file, raw); + response = await fn({ file, raw }); } catch (e) { throw open(e); } diff --git a/src/public/fs/types.ts b/src/public/fs/types.ts index 686386b..8dd918f 100644 --- a/src/public/fs/types.ts +++ b/src/public/fs/types.ts @@ -1,3 +1,5 @@ +import { IOfType } from '~/types'; + export type TSource = | string | string[] @@ -10,10 +12,16 @@ export type TCopyFilterFn = | ((src: string, dest: string) => boolean) | ((src: string, dest: string) => Promise); -export type TContentFn = ( - file: string, - raw?: string -) => string | void | Promise; +export type TContentFn = (data: { + file: string; + raw?: string; +}) => string | void | Promise; + +export type TJsonFn = (data: { + file: string; + raw?: string; + json?: IOfType; +}) => IOfType | void | Promise | void>; /** * Options taken by read *fs* functions. diff --git a/src/public/fs/write/write.ts b/src/public/fs/write/write.ts index e611df5..d737dd6 100644 --- a/src/public/fs/write/write.ts +++ b/src/public/fs/write/write.ts @@ -29,7 +29,7 @@ export async function each( if (typeof raw === 'function') { try { - raw = await raw(file); + raw = await raw({ file }); } catch (err) { throw open(err); }