I am currently working on fetching data from an external API and displaying it.
In order to enhance flexibility, I am aiming to completely separate the API integration from my code and use custom-defined data structures instead.
Here is a brief visual overview: https://i.stack.imgur.com/cxjaU.png
To illustrate this concept further, let's consider an example:
Imagine we are dealing with data related to people:
While API v1.0 returns {"name": "John"}
, API v1.1 might return {"pName": "John"}
.
To avoid potential issues caused by minor changes in the API response, I plan to internally define two interfaces: one for parsing the API response and another as a structure for the data itself:
interface IPersonDataStructure {
name : string;
}
interface IPersonDataParser {
parse(input: string) : IPersonDataStructure;
}
My goal is to create a class that combines the parser and the data structure:
// This class utilizes any parser that implements IPersonDataParser
// And uses IPersonDataStructure
class Person {
}
However, I have hit a roadblock at this stage! I am unsure about how to effectively merge the two elements together!
I am not keen on having an instance per Person's instance:
let aPerson = new Person(new Parser(data))
As the parser should ideally be stateless (similar to a function).
The challenge lies in TypeScript restrictions which make it difficult to achieve this with classes:
class Parser implements IPersonDataParser {
static public function parse(data : string) : IPersonDataStructure {
return {...}
}
}
class Person {
private _data : IPersonDataStructure;
constructor(data : string, parser : IPersonDataParser) {
this._data = parser.parse(data)
}
}
Callbacks could be a viable solution, but only if I can verify their signature.
For instance, the following does not validate correctly:
type PersonDataParser = (data : string) => IPersonDataStructure;
// Oops.. argument is missing!
let aParser = () => {
return {...}
}
let aPerson = new Person('data', aParser)
Are there any suggestions on how to overcome this challenge?