LoginSignup
15
8

More than 3 years have passed since last update.

概要

Cloud FunctionsでCloud SQLを利用する際に手間取ったので手順をメモ

Google Cloud Platform

CloudFunctions for Firebase

Connecting to Cloud SQL
(公式ドキュメント/英語)

Cloud SQL設定

以下の順でインスタンスを作成

1, Google Cloud Platform > ナビゲーションメニュー > SQL

2019-09-24 11.24のイメージ.JPG

2, インスタンスの作成 > データベースを選択(MySQL or PostgreSQL) > インスタンスID/rootパスワード/リージョン/データベースのバージョンなどを設定
※DBパスワードは再発行できないそうなので、忘れないようにメモする!!!

2019-09-24 11.30のイメージ.JPG

3, テーブルを作成する
※Cloud ShellやSQLクライアントツールを使って作成できる。今回は省略


Functionsの設定

MySQL使用例(公式のデモを参照)

functions/index.js
const mysql = require('mysql');

const connectionName =
'<インスタンス接続名>';
const dbUser = '<任意のDBユーザー>';
const dbPassword = '<任意のDBユーザーのパスワード>';
const dbName = '<DB名>';

const mysqlConfig = {
  connectionLimit: 1,
  user: dbUser,
  password: dbPassword,
  database: dbName,
};

if (process.env.NODE_ENV === 'production') {
  mysqlConfig.socketPath = `/cloudsql/${connectionName}`;
}

let mysqlPool;

exports.mysqlDemo = (req, res) => {
    if (!mysqlPool) {
    mysqlPool = mysql.createPool(mysqlConfig);
  }

  mysqlPool.query('SELECT NOW() AS now', (err, results) => {
    if (err) {
      console.error(err);
      res.status(500).send(err);
    } else {
      res.send(JSON.stringify(results));
    }
  });
}

とりあえずこれで動く。
ORMを使用する際に設定が足りない場合はmysqlConfigを以下のように設定
例:

const config = {
  host: `/cloudsql/${connectionName}`,
  dialect: 'mysql',
  username: dbUser,
  password: dbPassword,
  database: dbName,
  dialectOptions: {
    socketPath: `/cloudsql/${connectionName}`
  },
};
15
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
8