具有Cloud SQL的Cloud Functions-类型上不存在属性'socketPath'

时间:2019-06-10 01:34:14

标签: firebase google-cloud-platform google-cloud-functions google-cloud-sql

我正在尝试通过Firebase Functions访问我的Google Cloud SQL数据库。我遵循了Google documentation,但它不是很好,并且遗漏了大量信息。

我将文档中的代码添加到了我的src\index.ts文件中,并填写了我的数据:

const mysql = require('mysql');

const connectionName =
  process.env.INSTANCE_CONNECTION_NAME || 'test';
const dbUser = process.env.SQL_USER || 'test';
const dbPassword = process.env.SQL_PASSWORD || 'test';
const dbName = process.env.SQL_NAME || 'test';

const mysqlConfig = {
  connectionLimit: 1,
  user: dbUser,
  password: dbPassword,
  database: dbName,
};
if (process.env.NODE_ENV === 'production') {
  mysqlConfig.socketPath = `/cloudsql/${connectionName}`;
}

// Connection pools reuse connections between invocations,
// and handle dropped or expired connections automatically.
let mysqlPool;

exports.mysqlDemo = (req, res) => {
  // Initialize the pool lazily, in case SQL access isn't needed for this
  // GCF instance. Doing so minimizes the number of active SQL connections,
  // which helps keep your GCF instances under SQL connection limits.
  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));
      console.log("Connected!")
    }
  });

  // Close any SQL resources that were declared inside this function.
  // Keep any declared in global scope (e.g. mysqlPool) for later reuse.
};

然后我尝试发布此消息以查看其是否有效,并且出现错误:

  

在package.json中未将模块'mysql'列为依赖项

因此我通过执行mysql

安装了npm install mysql

然后我再次运行它,这次我得到了错误:

  

src / index.ts(23,15):错误TS2339:类型'{connectionLimit:number;不存在属性'socketPath'用户:字符串;密码:字符串;数据库:字符串; }'

这是怎么回事?我已经正确安装了吗?我很迷茫,文档似乎没有提供很多解决方案。谢谢!

1 个答案:

答案 0 :(得分:2)

这似乎是一个TypeScript错误,其中会推断出config对象的接口,然后您尝试在该对象上添加一个未声明的额外字段。换句话说,来自Google的示例代码是JavaScript,您正在使用TypeScript并遇到TS错误。

认为,您应该可以调整mysqlConfig的声明以包含一个socketPath属性(设置为null),并且都应该可以。换句话说,将mysqlConfig的定义更改为:

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