Learn how to write a URL shortener with Terrence.
init
command:
main.rs
file:
init
command takes care
of this as well, leaving us with the following Cargo.toml
:
init
command also created a new Shuttle project for us. This starts an
isolated container in Shuttle’s infrastructure.
Now, to deploy:
sqlx
dependency to Cargo.toml
and change
one line in main.rs
:
rocket
function, Shuttle
will
automatically provision a Postgres database for you, create an account and hand
you back an authenticated connection pool which is usable from your application
code.
Lets deploy it and see what happens:
Shuttle
is completely empty - I’m going to need to
either connect to Postgres and create the schema myself, or write some sort of
code to automatically perform the migration. As I start to ponder this seemingly
existential question I decide not to overthink it. I’m just going to go with
whatever is easiest.
I connect to the database provisioned by Shuttle using
pgAdmin using the provided database URI and run the
following script:
id
used for the url lookup is a primary key, which is implicitly a
‘unique’ constraint, Postgres would create the index for me. Cool.
shorten
URLs and one to
retrieve URLs and redirect
the user.
I quickly created two stubs for the endpoints while I thought about the actual
implementation:
INSERT
statement. Hm - what about duplicates? I decided
not to overthink it 🤷.
redirect
method in a similar spirit. At this point I
started to panic as it was really getting close to the 10 minute mark. I’ll do a
SELECT *
and pull the first url that matches with the query id. If the id does
not exist, you get back a 404
:
DEPLOYED
dialog came up, I instantly tested it out: