繁体   English   中英

如何将 Firestore 中的二维地图转换为 Typescripts 接口类型

[英]How to convert a 2-dimensional map from Firestore into Typescripts interface type

我正在尝试从 Firebase 的 Firestore 获取字段值,该值的类型基本上是Map<string, Map<string, dynamic>> 如何在 TypeScript 中定义和反序列化这种对象?

Firestore 文档数据,用户字段导致问题

{
  "movies": {

  },
  "name": "watchlist #1",
  "users": {
    "userId": {
      "alias": "user",
      "notify": false,
    }
  }
}
export interface Watchlist {
    movies: Map<string, WatchlistMovie>,
    name: string
    users: Map<string, WatchlistUser>
}

export interface WatchlistMovie {
    watchedBy: string[]
}

export interface WatchlistUser {
    alias: string
    notify: boolean
}

export function toWatchlist(snapshot: admin.firestore.DocumentSnapshot): Watchlist {
    const data = snapshot.data()!!;
    return {
        movies: data.movies,
        name: data.name,
        users: data.users
    };
}

当我尝试更新用户字段时,我收到以下错误。

TypeError: watchlist.users.set is not a function

基本上你不能没有额外的包,类转换器非常适合它。 特别检查plainToClass 文档

这是示例代码:

import 'reflect-metadata';
import { plainToClass, Type } from 'class-transformer';
import { stringify } from 'querystring';

export class Watchlist {
  @Type(() => Map)
  movies: Map<string, WatchlistMovie>;

  name: string;

  @Type(() => Map)
  users: Map<string, WatchlistUser>;
}

export class WatchlistMovie {
  watchedBy: string[];
}

export class WatchlistUser {
  alias: string;
  notify: boolean;
}

const data = {
  movies: {
    Shrek: {
      watchedBy: ['Me', 'You']
    }
  },
  name: 'watchlist #1',
  users: {
    userId: {
      alias: 'user',
      notify: false
    }
  }
};

const converted = plainToClass(Watchlist, data);

const movieWatchList = new WatchlistMovie();
movieWatchList.watchedBy.push('abc');
converted.movies.set('Avatar', movieWatchList);
console.log(converted);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM