Skip to content

Commit 81cce40

Browse files
committed
✨ Adding files load utility.
Adding helpers to implement file load automatically.
1 parent c5d42fa commit 81cce40

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@
4242
"fastify-plugin": "^1.6.0",
4343
"pino": "^5.15.0",
4444
"pino-pretty": "^3.5.0",
45-
"ramda": "^0.26.1"
45+
"ramda": "^0.26.1",
46+
"readdir-enhanced": "^5.1.1"
4647
},
4748
"devDependencies": {
4849
"@babel/cli": "^7.7.7",

src/helpers/loadFiles.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { readFile } from 'fs'
2+
import { IResolvers } from 'graphql-tools'
3+
import { join } from 'path'
4+
import { compose, curry, mergeDeepRight } from 'ramda'
5+
import readdir from 'readdir-enhanced'
6+
7+
const deep = true
8+
9+
const makePath = curry((path: string, file: string): string => join(path, file))
10+
11+
const readFiles = (path: string, filter: string): Promise<Array<string>> => readdir(path, { deep, filter })
12+
13+
const loadContent = (path: string): Promise<string> => {
14+
return new Promise((resolve, reject) => {
15+
readFile(path, 'utf8', (err, data) => {
16+
if (err) return reject(err)
17+
resolve(data)
18+
})
19+
})
20+
}
21+
22+
const readContentFiles = async (path: string, files: Array<string>): Promise<string[]> => {
23+
return Promise.all(files.map(compose(loadContent, makePath(path))))
24+
}
25+
26+
const requireFiles = async (path: string, files: Array<string>): Promise<IResolvers> => {
27+
return files.map(makePath(path)).reduce((prev, curr) => {
28+
/* eslint @typescript-eslint/no-var-requires: "Off" */
29+
const cxt = require(`${curr}`)
30+
return mergeDeepRight(prev, cxt)
31+
}, {})
32+
}
33+
34+
export const loadSchemas = async (path: string, filter: string): Promise<string> => {
35+
const files = await readFiles(path, filter)
36+
const list = await readContentFiles(path, files)
37+
return list.join('\n')
38+
}
39+
40+
export const loadContext = async (dir: string, filter: string): Promise<IResolvers> => {
41+
const files = await readFiles(dir, filter)
42+
return requireFiles(dir, files)
43+
}

0 commit comments

Comments
 (0)