From 0545073c8c1ef191fc85199e7fdbe3220ac716d8 Mon Sep 17 00:00:00 2001 From: Fabien Schurter Date: Sat, 4 May 2024 15:06:56 +0200 Subject: [PATCH] feature: Implement custom JS helper import --- src/domain/helpers.js | 11 +++++++++++ tests/domain/helpers.test.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 src/domain/helpers.js create mode 100644 tests/domain/helpers.test.js diff --git a/src/domain/helpers.js b/src/domain/helpers.js new file mode 100644 index 0000000..5ce6a54 --- /dev/null +++ b/src/domain/helpers.js @@ -0,0 +1,11 @@ +const HELPER_FILE_PATH = 'helpers.mjs' + +export const importCustomHelpers = (withSrcDir, ifPathExists) => ( + withSrcDir((prefixWithSrcDir) => ( + ifPathExists( + prefixWithSrcDir(HELPER_FILE_PATH), + (filePath) => import(filePath), + {}, + ) + )) +) diff --git a/tests/domain/helpers.test.js b/tests/domain/helpers.test.js new file mode 100644 index 0000000..4e8f696 --- /dev/null +++ b/tests/domain/helpers.test.js @@ -0,0 +1,32 @@ +import { describe, it } from 'node:test' +import assert from 'node:assert' +import { withTempDir } from '#tests/helpers' +import * as fs from 'node:fs/promises' +import { join } from 'node:path' +import { withDir, ifPathExists } from '#src/utils/fs' +import { importCustomHelpers } from '#src/domain/helpers' + +describe('#src/domain/helpers', () => { + describe('importCustomHelpers()', () => { + it('parses exports from a `helpers.js` file', async () => { + await withTempDir(async (prefixWithTempDir) => { + const srcDirPath = prefixWithTempDir('src') + const filePath = join(srcDirPath, 'helpers.mjs') + + await fs.mkdir(srcDirPath) + await fs.writeFile(filePath, ` +export const sayHello = () => 'Hello World!' + +export const add2 = (num) => num + 2 +`) + + const helpers = await importCustomHelpers(withDir(srcDirPath), ifPathExists) + + assert('sayHello' in helpers) + assert('add2' in helpers) + assert.strictEqual(helpers.sayHello(), 'Hello World!') + assert.strictEqual(helpers.add2(4), 6) + }) + }) + }) +})