LoginSignup
0
0

More than 3 years have passed since last update.

access cloud sql (my sql) from firebase functions

Posted at
index.ts
import * as functions from 'firebase-functions';

const mysql = require("promise-mysql");

// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript
//
export const helloWorldCall = functions
  .region("asia-northeast1")
  .https.onCall((data, context) => {
    return "Hello from Firebase! Test onCall";
  });

 // export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account/key.json
 // export CLOUD_SQL_CONNECTION_NAME='<MY-PROJECT>:<INSTANCE-REGION>:<MY-DATABASE>'
 // export DB_USER='my-db-user'
 // export DB_PASS='my-db-pass'
 // export DB_NAME='my_db'

// [START cloud_sql_mysql_mysql_create_socket]
const createUnixSocketPool = async (config:any) => {
   const dbSocketPath = "/cloudsql"

   // Establish a connection to the database
   return await mysql.createPool({
      user: "root", // e.g. 'my-db-user'
      password: "******", // e.g. 'my-db-password'
      database: "geography", // e.g. 'my-database'
       // If connecting via unix domain socket, specify the path
     socketPath: `${dbSocketPath}/extended-song-12345:asia-northeast1:test`,
     // Specify additional properties here.
     ...config
   });
 }
 // [END cloud_sql_mysql_mysql_create_socket]

const createPool = async () => {
  const config = {
    // [START cloud_sql_mysql_mysql_limit]
    // 'connectionLimit' is the maximum number of connections the pool is allowed
    // to keep at once.
    connectionLimit: 5,
    // [END cloud_sql_mysql_mysql_limit]

    // [START cloud_sql_mysql_mysql_timeout]
    // 'connectTimeout' is the maximum number of milliseconds before a timeout
    // occurs during the initial connection to the database.
    connectTimeout: 10000, // 10 seconds
    // 'acquireTimeout' is the maximum number of milliseconds to wait when
    // checking out a connection from the pool before a timeout error occurs.
    acquireTimeout: 10000, // 10 seconds
    // 'waitForConnections' determines the pool's action when no connections are
    // free. If true, the request will queued and a connection will be presented
    // when ready. If false, the pool will call back with an error.
    waitForConnections: true, // Default: true
    // 'queueLimit' is the maximum number of requests for connections the pool
    // will queue at once before returning an error. If 0, there is no limit.
    queueLimit: 0, // Default: 0
    // [END cloud_sql_mysql_mysql_timeout]

    // [START cloud_sql_mysql_mysql_backoff]
    // The mysql module automatically uses exponential delays between failed
    // connection attempts.
    // [END cloud_sql_mysql_mysql_backoff]
  };

  return await createUnixSocketPool(config);
};

let pool:any;
createPool()
  .then(async (p: any) => {
    pool = p;
  })
  .catch((err) => {
    process.exit(1);
  });

export const helloWorldHttp = functions
  .region("asia-northeast1")
  .https.onRequest(async (req, res) => {

   const stmt = 'SELECT city  FROM cities WHERE country =?';
   const rawdata = await pool.query(stmt, ['CHINA']);
   const dataString = JSON.stringify(rawdata);
   const rows = JSON.parse(dataString);
   console.log(rows);


   res.send(
      "Hello from Firebase! Test onRequest "+ rows[0].city
    );
  });

0
0
1

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
0
0