Is there a best practice way of storing data collected from an external API to be shared between many classes in my TypeScript app?
I have many classes that all want to interact with many different resources collected from this external API, but I do not want to keep making API requests to this external service of course. So I'm thinking of some kind of data store that will hold all this data, then my classes and pluck any data they want from this data store.
This only needs to be done per request in memory, so I'm not wanting a DB/Redis or anything here.
Would something basic like this work?
//
// storage.ts
//
export const storage: SomeStorageInterface = {
customer: {},
subscription: {},
};
//
// Customer.ts
//
import { storage } from "./storage.ts";
export class Customer {
public async get(id: string) {
const request = await axios.get(`https://someurl/customer/${id}`);
storage.customer = request.response.data // stored in "data store" for use elsewhere
}
}
//
// Subscription.ts
//
import { storage } from "./storage.ts";
export class Subscription {
public async getByCustomerEmail() {
const email = storage.customer.email // fetched from "data store"
const request = await axios.get(`https://someurl/subscription/by/email/${email}`);
storage.subscription = request.response.data // stored in "data store" for use elsewhere
}
}
// index.ts
import { storage } from "./storage.ts";
const customer = new Customer();
const subscription = new Subscription();
await customer.get("1234-5678");
await subscription.getByCustomerEmail();
// console.log(storage.customer) = { id: "1234-5678", email: "someone@somewhere.com", ... }
// console.log(storage.subscription) = { id: "abc1234", amount: 100000, ... }
This is completely untested hypothetical pseudo code but it shows the principal I am trying to acheive.
I can store data fetched from the Customer class and then use that data later on in the request in the Subscription class. Then I can even get this data from my index.ts and then use this to return to the user in my express route if I wanted.
Let's assume I have procedures in place to know that storage.customer will be populated before Subscription tries to access data from it.
Would the above work? Would it completely fail? Are there better methods to achieve my goal here?
I can't stress enough, this only needs to be per request, per user, I do not need or desire any persistence such as a database/redis/memcached etc.