Skip to content

Instantly share code, notes, and snippets.

@BoManev
Last active August 7, 2023 01:42
Show Gist options
  • Save BoManev/cedd52d341fbdd0d2834e09a3e05eaa0 to your computer and use it in GitHub Desktop.
Save BoManev/cedd52d341fbdd0d2834e09a3e05eaa0 to your computer and use it in GitHub Desktop.
Example how to call EmailOctopus API using tRPC and zod
import { z } from "zod";
import { createTRPCRouter, publicProcedure } from "~/server/api/trpc";
import { env } from "../../../env.mjs";
import { TRPCError } from "@trpc/server";
const Sub = z.object({
id: z.string(),
});
export const SubscriptionRouter = createTRPCRouter({
subscribe: publicProcedure
.input(z.object({ email: z.string().email("Invalid email!") }))
.mutation(async ({ input }) => {
let res: unknown;
try {
res = await fetch(`https://emailoctopus.com/api/1.6/lists/${env.EOCTO_LIST_ID}/contacts`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"api_key": env.EOCTO_API_KEY,
"email_address": input.email,
"status": "SUBSCRIBED",
"tags": [
"origin"
],
})
}).then(res => res.json());
}
catch (error) {
console.log(error);
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Request Failed! Please try again later.",
});
}
console.log(res);
const parsed = Sub.safeParse(res);
console.log(parsed);
if (parsed.success) {
return parsed.data;
} else {
throw new TRPCError({
code: "CONFLICT",
message: "Already subscribed!",
});
}
}),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment