Recently I was working with the Supabase SDK on a personal project and inside this project, I am using the .rpc()
method to call a SQL function. This function attempts to aggregate data around a user’s current link stats; how many there are, what’s being clicked, etc.
Without going into too much detail, using RPC functions is the suggested method to gain access to full SQL queries when using the Supabase SDK.
In the Supabase Docs, there is a reference about how to handle Typescript with the QueryData
type, however, this only seems to apply for .from
() calls and doesn’t work for the .rpc()
function call 🤦♂️
For the the time being I’ve decided to create a wrapper function that applies the desired type at the return
import { getServerClient } from '@/utils/server/getServerClient'
export type LinkStatsRpcReturn = {
links_created: number
total_clicks: number | null
conversion_rate: number | null
top_referrer: string | null
}
export async function getLinkStats() {
const supabase = getServerClient()
const { data, error } = await supabase.rpc('get_link_stats').single()
if (error) {
throw error
}
return data as LinkStatsRpcReturn
}
Now I can call getLinkStats
and the returned object is properly typed 🎉
I am still curious if there is a more refined approach to typing an .rpc()
call where one could avoid creating the additional helper method 💭 I admittedly didn’t dig too far into the source code on this one, but I’ll update this post if I return to the subject in the future.