Edge function to fetch fx rates every hour and write to a DB in Supabase
- Deno edge functions from Supabase
- Supabase tables to store data in Postgres
- PG_NET plugin from Supabase to make edge function calls to add data table
- PG_CRON plugin to call a corn job to add data periodically.
- Oak server. Think express for Deno runtime.
- Deno runtime because supabase supports it. (Almost has Node.js parity for APIs, making porting over easy)
- Sign up for some service that provides FX rates.
- Sign up for supabase
- Create a table called 'fx-rates' that is of the schema described below
create table
public.fx - rates (
id uuid not null default gen_random_uuid (),
timestamp timestamp with time zone null default now(),
base character varying null,
quote character varying null,
price real null,
constraint fx - rates_pkey primary key (id)
) tablespace pg_default;
- Setup RLS policies to allow access to our DB
- Enable extension
PG_CRON
andPG_NET
to allow for cron jobs and requests over https - Install the supabase CLI locally and link your project.
supabase functions new [FUNCTION_NAME]
will create a edge functionsupabase function deploy [FUNCTION_NAME]
will deploy them to the edge.supabase secrets set KEY VALUE
to set the secret obtained from step 1.- Run the below query in SQL_EDITOR to enable the cron job.
select
cron.schedule(
'fetch-fxrates-every-hr', -- name of cron
'1 * * * *', -- every hour
$$
select
net.http_post(
url:='PROJECT_URL/functions/v1/fetch-fxrates',
headers:='{"Content-Type": "application/json", "Authorization": "Bearer SERVICE_ROLE_TOKEN"}'::jsonb
) as request_id;
$$
);
- Get the
SERVICE_ANON_TOKEN
from your project to make the requests.
This will fetch the fxrates from here and store them in our PG table in supabase
To hit the only endpoint of this function
curl -i --location --request POST 'PROJECT_URL/functions/v1/fetch-fxrates' \
--header 'Authorization: Bearer SERVICE_ROLE_TOKEN' \
--header 'Content-Type: application/json'
This exposes a endpoint to read and set data to our table with the endpoint PROJECT_URL/functions/v1/fx-server/
ENDPOINT
=PROJECT_URL/functions/v1/fx-server/
For health check of this server hit /
curl -i --location --request GET ENDPOINT \
--header 'Authorization: Bearer SERVICE_ROLE_TOKEN
To get all fx rates entries of a base
and quote
currency. Both are 3 letter uppercase country codes like INR
, USD
etc.
curl -i --location --request GET ENDPOINT/[base_currency]/[quote_currency] \
--header 'Authorization: Bearer SERVICE_ROLE_TOKEN'
To set a price for a base
and quote
currency.
Make sure base
, quote
are 3 letter currency code. price
needs to be a float
curl -i --location --request PSOT ENDPOINT \
--header 'Authorization: Bearer SERVICE_ROLE_TOKEN' \
--header 'Content-Type: application/json' \
--data '{"base":"USD", "quote":"INR", "price": 81.01}'
PROJECT_URL
is https://qodaqyywtayabxzvhjoc.supabase.co
SERVICE_ANON_TOKEN
is ...