Tutorial: Serverless Backend With Firebase Function + Express + Sequelize + Cloud SQL
Required Stack:
Firebase
Firebase Function
Express
Sequelize ORM
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 databasemodels
, contains all models for your projectmigrations
, contains all migration filesseeders
, contains all seed files
> Setup config folder
In config folder, change config.json
to config.js
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



Try to create another 2 model, for example, create model for Courses and Lessons
Last updated
Was this helpful?