Created
December 26, 2024 08:50
-
-
Save truongluu/0f4f12c17c3e75ca461dc29b1b95255f to your computer and use it in GitHub Desktop.
Example Using Inversityjs lib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Container, inject, injectable, named } from "inversify"; | |
import { readFile } from "node:fs/promises"; | |
import * as path from "node:path"; | |
interface IParser<T = string> { | |
parse(data: string): T; | |
} | |
@injectable() | |
class JsonParser implements IParser<JSONType> { | |
parse(data: string) { | |
return JSON.parse(data); | |
} | |
} | |
@injectable() | |
class FileParser implements IParser { | |
parse(data: string) { | |
return data; | |
} | |
} | |
interface IFileReader<T> { | |
read(filepath: string): Promise<string>; | |
parse(): T; | |
} | |
const TYPES = { | |
IParser: Symbol.for("IParser"), | |
// Not entirely necessary for this example, but just to demonstrate how it works. | |
IFileReader: Symbol.for("IFileReader"), | |
}; | |
const TAGS = { | |
JsonParser: "JsonParser", | |
FileParser: "FileParser", | |
}; | |
@injectable() | |
class FileReader implements IFileReader<string> { | |
private parser: IParser; | |
private contents?: string; | |
constructor(@inject(TYPES.IParser) @named(TAGS.FileParser) parser: IParser) { | |
this.parser = parser; | |
} | |
async read(filepath: string): Promise<string> { | |
this.contents = await readFile(filepath, "utf-8"); | |
return this.contents; | |
} | |
parse() { | |
if (!this.contents) throw new Error("No contents to parse"); | |
return this.parser.parse(this.contents); | |
} | |
} | |
type JSONType = Record<string, any>; | |
const container = new Container(); | |
container | |
.bind<IParser>(TYPES.IParser) | |
.to(FileParser) | |
.whenTargetNamed(TAGS.FileParser); | |
container | |
.bind<IParser<JSONType>>(TYPES.IParser) | |
.to(JsonParser) | |
.whenTargetNamed(TAGS.JsonParser); | |
container.bind<IFileReader<any>>(TYPES.IFileReader).to(FileReader); | |
async function main() { | |
const jsonFileReader = container.getNamed<IFileReader<JSONType>>( | |
TYPES.IFileReader, | |
TAGS.JsonParser | |
); | |
const fileReader = container.getNamed<IFileReader<string>>( | |
TYPES.IFileReader, | |
TAGS.FileParser | |
); | |
await jsonFileReader.read(path.resolve(process.cwd(), "./data/example.json")); | |
await fileReader.read(path.resolve(process.cwd(), "./data/example.txt")); | |
console.log(fileReader.parse()); | |
console.log(jsonFileReader.parse()); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment