如何从Firebase云功能访问firestore.Timestamp

时间:2018-04-20 12:53:09

标签: node.js typescript firebase google-cloud-firestore google-cloud-functions

我们正在将Firestore Date对象转换为新的Timestamp Objects

我们通过导入firestore

在前端成功完成了这项工作
import { firestore } from 'firebase';

然后用firestore.Timestamp

替换所有Date对象类型
  startDate: firestore.Timestamp;

问题是我似乎找不到在节点中访问Timestamp的方法。

我已经尝试记录管理员和函数对象,但似乎无法找到所有的时间戳

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
...
console.log(functions)
console.log(admin)

这些是我尝试过的,他们都返回'未定义时存在时间戳'

import * as firebase from 'firebase';
...
firebase.firestore.Timestamp.now()
const firebase = require('firebase')   
...
firebase.firestore.Timestamp.now()
import * as admin from 'firebase-admin';
...
admin.firestore.Timestamp.now()

这是我的package.json dependancies

"dependencies": {
    "@sendgrid/mail": "^6.2.1",
    "@types/node-fetch": "^1.6.8",
    "chai": "^4.1.2",
    "chai-as-promised": "^7.1.1",
    "cors": "^2.8.4",
    "encodeurl": "^1.0.2",
    "fetch": "^1.1.0",
    "firebase": "^4.13.0",
    "firebase-admin": "^5.12.0",
    "firebase-functions": "^1.0.1",
    "generator-karma": "^2.0.0",
    "google-distance": "^1.0.1",
    "mailgun-js": "^0.13.1",
    "moment": "^2.22.1",
    "node-fetch": "^2.1.2",
    "request": "^2.85.0",
    "sinon": "^4.0.1",
    "typescript": "^2.8.3"
},
"private": true,
"devDependencies": {
    "@angular/cli": "^1.7.4",
    "@types/cors": "^2.8.3",
    "@types/jasmine": "^2.6.6",
    "ts-loader": "^3.5.0",
    "webpack-node-externals": "^1.7.2"
}

5 个答案:

答案 0 :(得分:10)

随着Firebase Functions V2.0的发布,它们似乎已在Firebase Admin SDK软件包中添加了时间戳支持。

看看官方文档here

import { firestore } from 'firebase-admin';
...
const now = firestore.Timestamp.now()

答案 1 :(得分:5)

在这个时刻,时间戳在节点的@google-cloud/firestore npm模块的最新版本中根本不可用。您还可以看到它未包含在API docs中。也许它会在下一版@google-cloud/firestore中添加。

答案 2 :(得分:2)

我遇到了同样的问题,因此在此创建了Firebase Firestore时间戳的基本节点模块https://www.npmjs.com/package/firebase-firestore-timestamp

来自https://www.gstatic.com/firebasejs/4.13.0/firebase-firestore.js

的基本代码端口

答案 3 :(得分:0)

由于您需要在云函数中使用它,因此您正在使用触发器(onCreate,onUpdate ...等),该触发器通过 snap 参数传递时间戳。您可以按以下方式使用它。 (它与我合作)

exports.newUserCreated = functions.firestore.document('users/{userId}').onCreate(async (snap, context) => {
firestore.collection(`users/${userID}/lists`).add({
    'created_time': snap.updateTime,
    'name':'new list name',
}).then(documentReference => {
    console.log("list created");
    return null;
  }).catch(error => {
    console.error('Error creating list', error);
    process.exit(1);
});

});

答案 4 :(得分:-1)

这从节点对我有用:

firebase = require('firebase')
firebase.firestore.Timestamp