Skip to content

Commit

Permalink
feat(exposed/file): adds json
Browse files Browse the repository at this point in the history
  • Loading branch information
rafamel committed Apr 26, 2019
1 parent b60c804 commit 6e7efb2
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/exposed/file/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as json } from './json';
31 changes: 31 additions & 0 deletions src/exposed/file/json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import path from 'path';
import fs from 'fs-extra';
import { exists } from '~/utils/file';
import core from '~/core';
import { IOfType, TScript } from '~/types';
import { rejects } from 'errorish';

/**
* Reads a JSON `file` and passes it as an argument to a callback `fn`. If the callback returns an object, **`file` will be overwritten** with its contents. `file` can be relative to the project's directory.
* @returns A `TScript`, as a function, that won't be executed until called by `kpo` -hence, calling `json` won't have any effect until the returned function is called.
*/
export default function json(
file: string,
fn: (json: IOfType<any>) => IOfType<any> | void | Promise<IOfType<any> | void>
): TScript {
return async function json(): Promise<void> {
if (!path.isAbsolute(file)) {
const paths = await core.paths();
file = path.join(paths.directory, file);
}

await exists(file, { fail: true });
const json = await fs.readJSON(file).catch(rejects);
const response = await fn(json);
if (response) {
await fs
.writeFile(file, JSON.stringify(response, null, 2))
.catch(rejects);
}
};
}
1 change: 1 addition & 0 deletions src/exposed/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './exec';
export * from './file';
export * from './prompts';
export * from './tags';
export { default as options } from './options';

0 comments on commit 6e7efb2

Please sign in to comment.