Tutorial: Serverless Backend With Firebase Function + Express + Sequelize + Cloud SQL

Required Stack:

  1. Firebase

  2. Firebase Function

  3. Express

  4. Sequelize ORM

  5. Cloud SQL

> Initializing Firebase Function

1. Install Firebase CLI in Project Directory

npm install -g firebase-tools

2. login to firebase via terminal

firebase login

3. initializing firebase functions

firebase init functions

> CD Functions in Terminal and Install Dependencies & Dev Dependencies

Express JS

npm install express

Sequelize ORM

npm install --save sequelize

MySql2

npm install --save mysql2

body-parser

npm i body-parser

> Setup Cloud SQL

Create New Project in Google Cloud Platform

Go to SQL, and create instance

Choose MySQL

Enable Compute Engine API

Create MySQL Instance

CloudSQL Instance Successfully Created

> Setup Sequelize in Functions

Install Sequelize CLI

npm install --save-dev sequelize-cli

Init Project

npx sequelize-cli init

This will create following folders

  • config, contains config file, which tells CLI how to connect with database

  • models, contains all models for your project

  • migrations, contains all migration files

  • seeders, contains all seed files

> Setup config folder

In config folder, change config.json to config.js

Replace config.js with code bellow:

module.exports = {
  HOST: "127.0.0.1",
  USER: "root",
  PASSWORD: "***********",
  DB: "[DB_NAME]",
  dialect: "mysql",
  socketPath: "INSTANCE_CONECTION_NAME",
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000,
  },
};

> Setup model folder

replace index.js file with code bellow:

'use strict';

const dbConfig = require("../config/config.js");
const Sequelize = require("sequelize");
const db = {};

const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
  host: dbConfig.HOST,
  dialect: dbConfig.dialect,
  dialectOptions: {
    socketPath: `/cloudsql/${dbConfig.socketPath}`,
  },
  pool: {
    max: dbConfig.pool.max,
    min: dbConfig.pool.min,
    acquire: dbConfig.pool.acquire,
    idle: dbConfig.pool.idle,
  },
});

db.Sequelize = Sequelize;
db.sequelize = sequelize;

module.exports = db;

> Generate Model

npx sequelize-cli model:generate --name {modelName} --attributes {FieldName}:{FieldType}

example

npx sequelize-cli model:generate --name Users --attributes user_name:string,user_email:string

it creates 2 file, users.js in models folder and migration file in migrations folder

users.js
migration file

Try to create another 2 model, for example, create model for Courses and Lessons

Last updated

Was this helpful?