Typescript类对象存储到Firebase数据库

时间:2018-07-13 05:55:56

标签: typescript firebase-realtime-database typescript-class

我定义了一个打字稿类,如下所示:

export class UserModel{
    private _name:string
    private _email:string
    private _userId:string
    private _teamId:string
    private _avatar:string
    private _teamName:string

    constructor(name:string, email:string, userId:string, teamId:string, avatar:string, teamName:string){
        this._name = name
        this._email = email
        this._userId = userId
        this._teamId = teamId
        this._avatar = avatar
        this._teamName = teamName
    }

    get name():string{
        return this._name
    }

    set name(val:string){
        this._name = val
    }

    get email():string{
        return this._email
    }

    set email(val:string){
        this._email = val
    }

    get userId():string{
        return this._userId
    }

    set userId(val:string){
        this._userId = val
    }

    get teamId():string{
        return this._teamId
    }

    set teamId(val:string){
        this._teamId = val
    }

    get avatar():string{
        return this._avatar
    }

    set avatar(val:string){
        this._avatar = val
    }

    get teamName():string{
        return this._teamName
    }
}

字段被设为私有,并使用getter和setter进行访问。效果很好,除了当我将对象存储到firebase db中时,它使用_ e.g

存储
{
"_name":"vik,
"_email": "blas@gmal.com"
...
}

这破坏了我的整体代码,因为下次我重新渲染它时,我的属性名称现在已从name更改为_name。

有没有一种方法,当我将该对象保留到firebase时,它将存储它而不包含_

请告知

2 个答案:

答案 0 :(得分:0)

您将必须编写代码以将所有对象值映射到具有要存储在数据库中的确切字段名称的对象中。 Firebase SDK除了为简化操作而编写的内容外,没有为此提供任何快捷方式。

答案 1 :(得分:0)

我可能会在 TypeScript 地狱中遭受漫长而痛苦的死亡,但这是我在保存到 Firestore 之前从类实例递归创建对象的方法。我告诉自己,对于这个 - 并且只有这个 - TypeScript 方法马虎是可以的,因为无论如何这是离开 TypeScript 世界之前的最后一步。

核心方法:

function toObjectRecursive (a: {[key: string]: any}) : object {
  a = Object.assign({}, a);

  const keys = Object.keys(a);

  const okObjectConstructorNames = [
    "function Array() { [native code] }",
    "function Object() { [native code] }"
  ]

  for (let i = 0; i < keys.length; i += 1) {
    const key = keys[i];
    const val = getProperty(a, key)
    const typename = typeof val;
    const constructor = val !== undefined && val !== null ? val.constructor.toString() : "";

    if (typename === "object" && okObjectConstructorNames.indexOf(constructor) === -1) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      setProperty(a, key, toObjectRecursive(a[key]))
    }
  }

  return a;
}

你还需要两个助手(我会更新引文)

export function getProperty<T, K extends keyof T> (o: T, propertyName: string): T[K] {
  return (o[propertyName as K]); // o[propertyName] is of type T[K]
}

export function setProperty<T, K extends keyof T> (o: T, propertyName: string, val: T[K]) {
  o[propertyName as K] = val; // o[propertyName] is of type T[K]
}