【问题标题】:How to convert a 2-dimensional map from Firestore into Typescripts interface type如何将二维地图从 Firestore 转换为 Typescripts 接口类型
【发布时间】:2019-09-04 09:12:37
【问题描述】:

我正在尝试从 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

【问题讨论】:

    标签: typescript firebase google-cloud-firestore


    【解决方案1】:

    基本上你不能没有额外的包,Class transformer 非常适合它。特意查看plainToClass documentation

    这里是示例代码:

    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);
    

    【讨论】:

    • 欢迎您。适用于多种用途:) 但有时它会出现一些嵌套和更复杂结构的问题。虽然我总是解决我需要的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 2021-11-16
    • 2011-07-31
    • 2021-01-17
    • 2017-01-11
    相关资源
    最近更新 更多