From 1cd195c02e96b96ce8a9c1e620f5ececef1b9a52 Mon Sep 17 00:00:00 2001 From: Rafa Mel Date: Fri, 12 Apr 2019 01:08:42 +0200 Subject: [PATCH] feat(parse): adds readFile and IScripts type --- src/parse/read-file.ts | 24 ++++++++++++++++++++++++ src/types.ts | 10 ++++++++++ 2 files changed, 34 insertions(+) create mode 100644 src/parse/read-file.ts diff --git a/src/parse/read-file.ts b/src/parse/read-file.ts new file mode 100644 index 0000000..49b1d3a --- /dev/null +++ b/src/parse/read-file.ts @@ -0,0 +1,24 @@ +import fs from 'fs'; +import path from 'path'; +import pify from 'pify'; +import yaml from 'js-yaml'; +import { IScripts } from '~/types'; +import ensure from '~/utils/ensure'; + +export default async function readFile(file: string): Promise { + const { ext } = path.parse(file); + + switch (ext) { + case '.js': + return require(file); + case '.json': + return JSON.parse(await ensure.rejection(() => pify(fs.readFile)(file))); + case '.yml': + case '.yaml': + return yaml.safeLoad( + await ensure.rejection(() => pify(fs.readFile)(file)) + ); + default: + throw Error(`Extension not valid`); + } +} diff --git a/src/types.ts b/src/types.ts index 41b8e28..5e99be2 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,13 @@ import { LogLevelDesc } from 'loglevel'; +export interface IOfType { + [key: string]: T; +} + export type TLogger = LogLevelDesc; + +export type TScript = string | (() => Promise | void); + +export interface IScripts { + [key: string]: TScript | TScript[] | IScripts; +}