I come from Redux and I start to learn MST.
I try to introduce the logic of Token's refreshing professionally. I have already explained what it is supposed to:
- Client sends a request to the server
- Server answers every 60s code 401
- Client knows that when it is 401, it has to refresh token, send the request for refresh token
- Client after receiving a positive response from the server, is to repeat the action earlier.
For rectification, I use Boilerplate from Ignited (React-Native):
export const AuthenticationStoreModel = types .model("AuthenticationStore") .props({ isAuthenticationed: types.optional(types.boolean, false), }) .extend(withEnvironment) .extend(withRootStore) .actions((self) => ({ setAuthenticated(value: boolean) { self.isAuthenticationed = value }, refreshToken: flow(function* () { const authenticationApi = new AuthenticationApi(self.environment.api) const result: RefreshTokenResult = yield authenticationApi.refreshToken() if (result.kind === "ok") { return true } else { __DEV__ && console.tron.log(result.kind) return false } }), })) .actions((self) => ({ logout: flow(function* () { const authenticationApi = new AuthenticationApi(self.environment.api) const result: LogoutResult = yield authenticationApi.logout() if (result.kind === "ok") { self.setAuthenticated(false) } else if (result.kind === "unauthorized") { const result = yield self.refreshToken() if (result) { self.rootStore.authenticationStore.logout() } } else { __DEV__ && console.tron.log(result.kind) } }), }))
Well it works, but it's poorly written. How am I supposed to improve it? Can't do some middleware under it?
and how do I do some dependency injection for the AuthenticationApi() class.