i am struggling to write some typescript code using fp-ts
Below are the tasks that i want the algorithm to carry out:
Once a path is received from the command line, it should
- check if the given path exists
- search for all files in the directory and locate a file with the name
cratb.import
and one of the extensions ".json", ".yaml" or ".yml" - If the extension is ".json", parse the plain text into an object using
JSON.parse
. If it's ".yaml", use the js-yaml package to parse the plain text into an object withYAML.load
Here is the primary part of my code:
if(FpFs.pathExists(targetPath)){
const res = await pipe(
FpFs.readDir(targetPath),
TE.map((files) =>
O.fromNullable(files.find(e => e === `${dFileName}.yaml` || e === `${dFileName}.yml` || e === `${dFileName}.json`))
),
TE.map(
O.map(fileName =>
['json', 'JSON', 'yaml', 'YAML', 'yml', 'YML'].includes(getFileExtension(fileName))
? O.fromNullable(fileName)
: O.fromNullable(null)
)
),
TE.map(O.flatten),
TE.map(
O.map(
fileName =>
['json', 'JSON'].includes(getFileExtension(fileName))
? pipe(
FpFs.readFile(path.join(targetPath, fileName)),
TE.map(x => JSON.parse(x.toString()))
)
: pipe(
FpFs.readFile(path.join(targetPath, fileName)),
TE.map(x => YAML.load(x.toString()))
)
)
)
)()
if(E.isRight(res)){
if(O.isSome(res.right)){
res.right.value()
.then(res => {
if(E.isRight(res)){
return console.log(res.right)
}
})
}
}
console.log('Error in some point XD')
}else{
console.log(color.red(['ERROR']), `directory "${ importFilePath }" not found`)
}
I feel like there might be room for improvement in this code
Any suggestions would be greatly appreciated
Thank you