Skip to content

Commit

Permalink
feat: callRest helper
Browse files Browse the repository at this point in the history
  • Loading branch information
Tim Smart committed Mar 22, 2022
1 parent 52e532e commit 5c617b6
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
18 changes: 16 additions & 2 deletions DiscordREST/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import * as T from "@effect-ts/core/Effect"
import { tag } from "@effect-ts/system/Has"
import { Has, tag } from "@effect-ts/system/Has"
import Axios, { AxiosInstance, AxiosRequestConfig, Method } from "axios"
import * as Config from "../DiscordConfig"
import { createRoutes, Endpoints } from "../types"
import * as Http from "./http"
import { Response, RESTError } from "./types"

export interface DiscordREST extends Endpoints<AxiosRequestConfig> {
interface AxiosEndpoints extends Endpoints<AxiosRequestConfig> {}
export interface DiscordREST extends AxiosEndpoints {
_tag: "DiscordREST"
axios: AxiosInstance
}
Expand Down Expand Up @@ -81,3 +83,15 @@ const make = T.gen(function* (_) {
export const LiveDiscordREST = T.toLayer(DiscordREST)(make)

export const rest = T.accessServiceM(DiscordREST)

type InferResponse<T extends (...args: any[]) => Response<any>> = T extends (
...args: any[]
) => Response<infer R>
? R
: never

export const call = <K extends keyof AxiosEndpoints>(
method: K,
...args: Parameters<AxiosEndpoints[K]>
): T.Effect<Has<DiscordREST>, RESTError, InferResponse<AxiosEndpoints[K]>> =>
rest((r) => (r[method] as any)(...args))
9 changes: 4 additions & 5 deletions bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import * as CB from "callbag-effect-ts"
import * as Dotenv from "dotenv"
import { log } from "./Log"
import {
callRest,
DebugEnv,
fromDispatch,
gateway,
Expand All @@ -31,11 +32,9 @@ const pingPong = pipe(
fromDispatch("MESSAGE_CREATE"),
CB.filter((msg) => msg.content.startsWith("!ping")),
CB.forEach((msg) =>
rest((r) =>
r.createMessage(msg.channel_id, {
content: "Pong!",
}),
),
callRest("createMessage", msg.channel_id, {
content: "Pong!",
}),
),
)

Expand Down
2 changes: 1 addition & 1 deletion mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ export const DefaultEnv = DiscordEnv["+++"](LiveLog)

export { makeLayer as makeConfigLayer } from "./DiscordConfig"
export { gateway, fromDispatch, run } from "./DiscordGateway"
export { rest } from "./DiscordREST"
export { rest, call as callRest } from "./DiscordREST"

0 comments on commit 5c617b6

Please sign in to comment.