add example functions

This commit is contained in:
Shawn Erquhart
2024-11-13 16:05:43 -05:00
parent ade1dad16d
commit 381127fb44
5 changed files with 73 additions and 67 deletions

View File

@@ -1,59 +1,56 @@
import { components } from "./_generated/api";
import { Polar } from "@convex-dev/polar";
import { v } from "convex/values";
import { WebhookSubscriptionCreatedPayload$inboundSchema } from "@polar-sh/sdk/models/components";
import { query, internalMutation } from "./_generated/server";
import { components } from "./_generated/api";
import { Id } from "./_generated/dataModel";
const polar = new Polar(components.polar);
const polarComponent = new Polar(components.polar);
/*
export const addOne = mutation({
export const listProducts = query({
args: {},
handler: async (ctx, _args) => {
await numUsers.inc(ctx);
},
});
export const getCount = query({
args: {},
handler: async (ctx, _args) => {
return await numUsers.count(ctx);
},
});
export const usingClient = internalMutation({
args: {},
handler: async (ctx, _args) => {
await polar.add(ctx, "accomplishments");
await polar.add(ctx, "beans", 2);
const count = await polar.count(ctx, "beans");
return count;
},
});
export const usingFunctions = internalMutation({
args: {},
handler: async (ctx, _args) => {
await numUsers.inc(ctx);
await numUsers.inc(ctx);
await numUsers.dec(ctx);
return numUsers.count(ctx);
},
});
export const directCall = internalMutation({
args: {},
handler: async (ctx, _args) => {
await ctx.runMutation(components.polar.lib.add, {
name: "pennies",
count: 250,
handler: async (ctx) => {
return polarComponent.listProducts(ctx, {
includeArchived: false,
});
await ctx.runMutation(components.polar.lib.add, {
name: "beans",
count: 3,
shards: 100,
});
const count = await ctx.runQuery(components.polar.lib.count, {
name: "beans",
});
return count;
},
});
*/
export const getUserSubscriptions = query({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
return polarComponent.listUserSubscriptions(ctx, args.userId);
},
});
/**
* This function is called when a Polar webhook is received.
*
* The payload is provided as received from Polar, and the webhook signature is
* already verified before this function is called.
*/
export const polarEventCallback = internalMutation({
args: {
payload: v.any(),
},
handler: async (ctx, args) => {
switch (args.payload.type) {
// When creating a subscription, pass the user's id from your system into
// the metadata field. The same metadata will be passed back in the
// webhook, allowing you to add the user's Polar ID to the record in
// your database.
case "subscription.created": {
const payload = WebhookSubscriptionCreatedPayload$inboundSchema.parse(
args.payload
);
const userId = payload.data.metadata.userId;
await ctx.db.patch(userId as Id<"users">, {
polarId: payload.data.userId,
});
break;
}
}
},
});