const parseBody = (event: H3Event<EventHandlerRequest>) => pipe(
Effect.tryPromise({
try: (): Promise<unknown> => readBody(event, { strict: true }),
catch: () => new InvalidBodyError("Invalid body format"),
}),
)
const handlePlayerSearchEvent = (event: H3Event<EventHandlerRequest>): Effect.Effect<PlayerSearchResult, ParseError | HttpClientError, never> => {
return Effect.Do.pipe(
Effect.bind('body', () => parseBody(event).pipe(Effect.tap(Console.log), S.decodeUnknown(SearchPlayerEvent))),
Effect.let('region', ({ body }) => matchRegion(body.region)),
Effect.let('name', ({ body }) => pipe(splitByHash(body), Array.headNonEmpty)),
Effect.let('tagLine', ({ body, region }) => pipe(
splitByHash(body),
Array.get(1),
Option.getOrElse(() => region)
)),
Effect.bind('account', ({ region, name, tagLine }) =>
fetchEffect(RiotAccountResponseSchema)
(`https://${region}.api.riotgames.com/riot/account/v1/accounts/by-riot-id/${name}/${tagLine}`)),
Effect.bind('summoner', ({ account, region }) =>
fetchEffect(SummonerDataSchema)
(`https://${region}.api.riotgames.com/lol/summoner/v4/summoners/by-puuid/${account.puuid}`)),
Effect.bind('matchIds', ({ account, region }) =>
fetchEffect(S.Array(S.String))
(`https://${region}.api.riotgames.com/lol/match/v5/matches/by-puuid/${account.puuid}/ids?start=0&count=20`)),
Effect.bind('matches', ({ matchIds, region }) => pipe(
matchIds,
Array.map(matchId => fetchEffect(RiotMatchSchema)(`https://${region}.api.riotgames.com/lol/match/v5/matches/${matchId}`)),
(a) => Effect.all(a, { concurrency: 5, batching: true })
)
),
Effect.map(({ summoner, account, matches }) => ({ summoner, account, matches }))
);
}
export default defineEventHandler(async (event) => Effect.runPromise(handlePlayerSearchEvent(event)));