如何将Firebase的Timestamp实现为有效类型?

vlf7wbxs  于 2023-10-22  发布在  其他
关注(0)|答案(3)|浏览(137)

ts/ io-ts,我正在尝试将Firebase.Timestamp作为有效类型实现。但我总是出错。我可以创建一个正常的时间戳副本:

copyTimeStamp = {
  seconds : t.number,
  nanoseconds : t.number
}

但是如果我使用io-ts中的自定义编码类型将其推到firebase上,它不会存储为Timestamp属性,而只是一个普通的Map。

ev7lccsx

ev7lccsx1#

如果要在Firestore中写入时间戳类型字段,则必须使用原生JavaScript Date对象或Firestore SDK提供的Timestamp对象。你不能用你自己的物体来模拟它。

2wnc66cl

2wnc66cl2#

您需要从@react-native-firebase/firestore导入FirebaseFirestoreTypes
这就是:

import {FirebaseFirestoreTypes} from '@react-native-firebase/firestore';

...

type StateTypes = {
  created_at: FirebaseFirestoreTypes.Timestamp | null;
  updated_at: FirebaseFirestoreTypes.Timestamp | null;
}
qmelpv7a

qmelpv7a3#

您可以为Firebase时间戳创建io-ts编解码器

import { Timestamp } from '@firebase/firestore-types';
import * as t from 'io-ts';

为时间戳定义自定义编解码器:

const FirebaseTimestamp = new t.Type<Timestamp, { seconds: number; nanoseconds: number }, unknown>(
  'FirebaseTimestamp',
  
  // `is` checks if the input value is a Timestamp.
  (input): input is Timestamp => input instanceof Timestamp,
  
  // `validate` converts the input value to a Timestamp if possible.
  (input, context) => {
    if (input instanceof Timestamp) {
      return t.success(input);
    }
    if (typeof input === 'object' && typeof input.seconds === 'number' && typeof input.nanoseconds === 'number') {
      return t.success(new Timestamp(input.seconds, input.nanoseconds));
    }
    return t.failure(input, context);
  },
  
  // `encode` converts a Timestamp back to a plain object.
  (timestamp) => ({
    seconds: timestamp.seconds,
    nanoseconds: timestamp.nanoseconds
  })
);

相关问题