Skip to content

Commit

Permalink
fix(file-loader): fix absolutePath option not working on windows
Browse files Browse the repository at this point in the history
  • Loading branch information
Nikaple committed May 7, 2021
1 parent 7f6c61f commit f45bd04
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 16 deletions.
28 changes: 20 additions & 8 deletions lib/loader/file-loader.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { cosmiconfig, Options } from 'cosmiconfig';
import { parse as parseToml } from '@iarna/toml';
import { Config } from 'cosmiconfig/dist/types';
import { basename, dirname } from 'path';

const loadToml = function loadYaml(filepath: string, content: string) {
try {
Expand All @@ -23,6 +24,23 @@ export interface FileLoaderOptions extends Partial<Options> {
searchFrom?: string;
}

const getSearchOptions = (options: FileLoaderOptions = {}) => {
if (options.absolutePath) {
return {
searchPlaces: [basename(options.absolutePath)],
searchFrom: dirname(options.absolutePath),
};
}
const formats = ['toml', 'yaml', 'yml', 'json', 'js'];
return {
searchPlaces: [
...formats.map(format => `.env.${process.env.NODE_ENV}.${format}`),
...formats.map(format => `.env.${format}`),
],
searchFrom: options.searchFrom,
};
};

/**
* File loader loads configuration with `cosmiconfig`.
*
Expand All @@ -39,13 +57,7 @@ export interface FileLoaderOptions extends Partial<Options> {
*/
export const fileLoader = (options: FileLoaderOptions = {}) => {
return async (): Promise<Config> => {
const formats = ['toml', 'yaml', 'yml', 'json', 'js'];
const searchPlaces = options.absolutePath
? [options.absolutePath]
: [
...formats.map(format => `.env.${process.env.NODE_ENV}.${format}`),
...formats.map(format => `.env.${format}`),
];
const { searchPlaces, searchFrom } = getSearchOptions(options);
const loaders = {
'.toml': loadToml,
...options.loaders,
Expand All @@ -55,7 +67,7 @@ export const fileLoader = (options: FileLoaderOptions = {}) => {
...options,
loaders,
});
const result = await explorer.search(options.searchFrom);
const result = await explorer.search(searchFrom);

if (!result) {
throw new Error(`Failed to find configuration file.`);
Expand Down
9 changes: 1 addition & 8 deletions lib/typed-config.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,7 @@ export class TypedConfigModule {
validate = this.validateWithClassValidator.bind(this),
} = options;

let rawConfig: any;

try {
rawConfig = await load();
} catch (err) {
throw new Error(`Configuration load failed with error: ${err.message}`);
}

const rawConfig = await load();
if (typeof rawConfig !== 'object') {
throw new Error(
`Configuration should be an object, received: ${rawConfig}. Please check the return value of \`load()\``,
Expand Down

0 comments on commit f45bd04

Please sign in to comment.