A simple url shorter API built with nodejs running on Kubernetes in Google Cloud, using PostgreSQL for storage and cloud sql proxy.

Overview

Simple URL Shorter - Google Cloud - Kubernetes

A simple url shorter API built with nodejs running on Kubernetes in Google Cloud, using PostgreSQL for storage and cloud sql proxy.

Supports shortening url via post requests and redirects to full url if shortened ID exists in the database.

In dev mode you can also clear the table and get all database rows in a json format.

Usage

The Quickest way is to use Curl.

The short (optional) property is what your ideal shortened id would look like. If your desired ID is taken you will get an error message and you will need to create a different one. If you don't supply short a random available ID will be generated for you.

The full property is mandatory, and it will be the url that you will be redirected to.

curl -d '{"short":"gg", "full":"https://google.com"}' -H "Content-Type: application/json" -X POST http://server-ip/

After a successful Query you will get a piece of json that looks like this {"url":"http://server-ip/gg"} which is your shortened url.

Setup

  1. You will need to have a Google Cloud account setup and active (requires card).
  2. Install gcloud sdk.
  3. Install Docker and Kubectl.
  4. psql

- PostgreSQL Database -

  1. Create a PostgreSQL Instance in google cloud console and check the public ip.
  2. Create a service account and save the json file, this is will be used for cloud_sql_proxy.
  3. Start up cloud_sql_proxy and leave it running
./cloud_sql_proxy -instances=<projectname>tcp:5432 -credential_file=./credentials.json
  1. Login to the DB with psql
psql "host=127.0.0.1 port=5433 sslmode=disable dbname=<dbname> user=<dbuser>"
  1. Create the following table:
CREATE TABLE IF NOT EXISTS public.url (
short character varying(20) PRIMARY KEY,
full_ character varying(255) NOT NULL
);

- Create and upload docker image to google registry -

  1. export PROJECT_ID=<your project name> set this as an env variable so commands are easier to type.
  2. docker build --network=host -t gcr.io/${PROJECT_ID}/url-shortner:v1 .
  3. You can test the docker image by running docker run --rm -p 8080:8080 -it --entrypoint /bin/sh gcr.io/${PROJECT_ID}/url-shortner:v1 it will be on port 8080 in your browser.
  4. At this point you will need to setup gcloud by running gcloud init.
  5. Enable registry api gcloud services enable containerregistry.googleapis.com
  6. Get docker config gcloud auth configure-docker
  7. push the docker image docker push gcr.io/${PROJECT_ID}/url-shortner:v1

- Create Kubernetes Cluster -

  1. gcloud container clusters create url-cluster --zone europe-west2-c --zone is optional
  2. get kubectl config gcloud container clusters get-credentials url-cluster
  3. Copy kube-secrets-template.env to kube-secrets.env and update it with your database info.
  4. kubectl create secret generic envs --from-env-file=kube-secrets.env will allow the api to get access to the passwords in a safer way.
  5. To use cloud_sql_proxy in the cluster you will need to add the service account json as a secret. kubectl create secret generic cloudsql-sa-creds --from-file=credentials.json=credentials.json
  6. Now copy the deploy-template.yaml to deploy.yaml and replace <image>, <projectname>
  7. kubectl apply -f deploy.yaml this will create the api and cloud proxy.
  8. You can check their status with kubectl get pods
  9. To access the api properly I will use a LoadBalancer create it like this
kubectl expose deployment url-app-deployment --name=url-shortner-service --type=LoadBalancer --port 80 --target-port 8080
  1. To get the public ip (EXTERNAL-IP) of the balancer use kubectl get service this will be from where the app can be accessed. The api uses port 80 by default so you can copy and paste the ip into your browser, and you will get a curl command that you can copy nicely populated with the ip.

Dev

To develop the app you will need to fire up cloud_sql_proxy again if you want to use the remote database.

Copy the .env-template as .env and edit appropriately this is essentially a drop in replacement for kube-secrets.env but setup for a development environment.

To run the app do npm install && npm run debug if you want extra output from the debug module.

- Secret Dev Routes -

GET 127.0.0.1:8080/test/all_links will display all rows in the database.

GET 127.0.0.1:8080/test/clear_table will delete all rows.

You might also like...

Nodeparse - A lightweight, vanilla replacement for Express framework when parsing the HTTP body's data or parsing the URL parameters and queries with NodeJS.

Nodeparse - A lightweight, vanilla replacement for Express framework when parsing the HTTP body's data or parsing the URL parameters and queries with NodeJS.

nodeparse A lightweight, vanilla replacement for Express framework when parsing the HTTP body's data or parsing the URL parameters and queries with No

Jan 8, 2022

A web SQL interface to your Stripe account using Datasette.

Datasette, Stripe and tdog Or: Stripe Sigma Alternative Datasette is a web GUI for exploring SQLite datasets. Stripe handles online payments. Sigma is

Nov 27, 2022

Execute one command (or mount one Node.js middleware) and get an instant high-performance GraphQL API for your PostgreSQL database!

Execute one command (or mount one Node.js middleware) and get an instant high-performance GraphQL API for your PostgreSQL database!

PostGraphile Instant lightning-fast GraphQL API backed primarily by your PostgreSQL database. Highly customisable and extensible thanks to incredibly

Jan 4, 2023

AlaSQL.js - JavaScript SQL database for browser and Node.js. Handles both traditional relational tables and nested JSON data (NoSQL). Export, store, and import data from localStorage, IndexedDB, or Excel.

AlaSQL.js - JavaScript SQL database for browser and Node.js. Handles both traditional relational tables and nested JSON data (NoSQL). Export, store, and import data from localStorage, IndexedDB, or Excel.

Please use version 1.x as prior versions has a security flaw if you use user generated data to concat your SQL strings instead of providing them as a

Jan 9, 2023

Lovefield is a relational database for web apps. Written in JavaScript, works cross-browser. Provides SQL-like APIs that are fast, safe, and easy to use.

Lovefield Lovefield is a relational database written in pure JavaScript. It provides SQL-like syntax and works cross-browser (currently supporting Chr

Jan 3, 2023

An adapter-based ORM for Node.js with support for mysql, mongo, postgres, mssql (SQL Server), and more

An adapter-based ORM for Node.js  with support for mysql, mongo, postgres, mssql (SQL Server), and more

Waterline is a next-generation storage and retrieval engine, and the default ORM used in the Sails framework. It provides a uniform API for accessing

Jan 4, 2023

An easy-to-use multi SQL dialect ORM tool for Node.js

Sequelize Sequelize is a promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction s

Jan 4, 2023

An SQL-friendly ORM for Node.js

Objection.js Objection.js is an ORM for Node.js that aims to stay out of your way and make it as easy as possible to use the full power of SQL and the

Jan 5, 2023

Microsoft SQL Server client for Node.js

node-mssql Microsoft SQL Server client for Node.js Supported TDS drivers: Tedious (pure JavaScript - Windows/macOS/Linux, default) Microsoft / Contrib

Jan 4, 2023
Owner
null
Azure Data Studio is a data management tool that enables you to work with SQL Server, Azure SQL DB and SQL DW from Windows, macOS and Linux.

Azure Data Studio is a data management tool that enables working with SQL Server, Azure SQL DB and SQL DW from Windows, macOS and Linux.

Microsoft 7k Dec 31, 2022
Avocano is a sample dropship/fake product website with Cloud Run, Cloud SQL and Cloud Build

Avocano - A Fake Product Website Avocano is a sample dropship/fake product website, combining: Firebase Hosting front end, written with Lit, Cloud Run

Google Cloud Platform 9 Dec 9, 2022
ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

TypeORM is an ORM that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used

null 30.1k Jan 3, 2023
Database manager for MySQL, PostgreSQL, SQL Server, MongoDB, SQLite and others. Runs under Windows, Linux, Mac or as web application

Database manager for MySQL, PostgreSQL, SQL Server, MongoDB, SQLite and others. Runs under Windows, Linux, Mac or as web application

DbGate 2k Dec 30, 2022
Validate and auto-generate TypeScript types from raw SQL queries in PostgreSQL.

SafeQL Write SQL Queries With Confidence • Get started Install I would first recommend follow the instructions in the documentation. npm install --sav

null 747 Dec 28, 2022
Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server & SQLite

Prisma Quickstart • Website • Docs • Examples • Blog • Slack • Twitter • Prisma 1 What is Prisma? Prisma is a next-generation ORM that consists of the

Prisma 28k Jan 2, 2023
Ultimate Script to complete PostgreSQL-to-PostgreSQL Migration right after AWS DMS task done

Ultimate Script to complete PostgreSQL-to-PostgreSQL Migration right after AWS DMS task done

방신우 22 Dec 23, 2022
NodeJS PostgreSQL database performance insights. Locks, index usage, buffer cache hit ratios, vacuum stats and more.

Node Postgres Extras NodeJS port of Heroku PG Extras with several additions and improvements. The goal of this project is to provide powerful insights

Paweł Urbanek 68 Nov 14, 2022
A simple Node.js ORM for PostgreSQL, MySQL and SQLite3 built on top of Knex.js

bookshelf.js Bookshelf is a JavaScript ORM for Node.js, built on the Knex SQL query builder. It features both Promise-based and traditional callback i

Bookshelf.js 6.3k Jan 2, 2023