Created
January 11, 2023 11:13
-
-
Save sachitsac/a3cee2598eb0c88f246109b14d2d2518 to your computer and use it in GitHub Desktop.
How to add runtime type safety using zod when using external api's
This file contains 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
interface User { | |
id: number; | |
name: string; | |
email: string; | |
address?: string; | |
} | |
interface GetUserByIdParams { | |
id: User["id"]; | |
filter: { [k in keyof User]: User[k] }; | |
} | |
interface Weather { | |
summary: string; | |
max: number; | |
min: number; | |
chanceOfRain: number; | |
} | |
interface UserWeatherResponse { | |
user: User; | |
weather: Weather; | |
} | |
function getUserService() { | |
return { | |
getUserById: (id: User["id"]) => ({ | |
id, | |
name: "John Doe", | |
email: "[email protected]", | |
}), | |
}; | |
} | |
function getWeatherFromGoogleApi(address: string): Weather { | |
const responseFromGoogle = { | |
summary: "It will be a nice sunny day", | |
max: 20, | |
min: 20, | |
chanceOfRain: 0, | |
humidity: 10, | |
}; | |
return { | |
summary: responseFromGoogle.summary, | |
max: responseFromGoogle.max, | |
min: responseFromGoogle.min, | |
chanceOfRain: responseFromGoogle.chanceOfRain, | |
}; | |
} | |
function getWeatherService() { | |
return { | |
getWeatherForUser: (user: User) => | |
getWeatherFromGoogleApi(user.address ?? ""), | |
}; | |
} | |
const userService = getUserService(); | |
const weatherService = getWeatherService(); | |
export const getUserWeather = ( | |
params: GetUserByIdParams | |
): UserWeatherResponse => { | |
const user = userService.getUserById(params.id); | |
const weather = weatherService.getWeatherForUser(user); | |
return { | |
user, | |
weather, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment