我一直在为Firebase的Firestore进行包装。目前,我已经编写了一种Collection
类型,在很大程度上是Firestore Query
类的代理。这意味着它将大多数方法转发到基础查询,但是随后它将查询返回的内容包装到另一个Collection
中。这使我可以将查询方法链接在一起,同时仍保留Collection
类型。它允许我编写如下代码:
class Post {
static collection = "posts"
public title: string
public body: string
public created: Date
constructor(title: string, body: string, created: Date) {
this.title = title
this.body = body
this.created = created
}
}
// collection(Post) just returns a Collection<Post>,
// and after the where method it's still a Collection<Post>
let posts = collection(Post).where("created", "<", new Date)
而且我已经能够编写Collection<Model>
的类型定义,以便TypeScript理解它包含Query
中的所有方法,但是这些方法的返回类型将始终为{{ 1}}。这样就可以很好地完成代码。解释为什么所有这些对我都有益的原因需要花很长时间才能解释,这与我的问题无关。
我的问题是,我实际上希望能够以完全不同的方式执行此操作。我想使Collection<Model>
本身可以作为Post
的代理,就像Query
现在所做的那样。除了主要区别在于,然后我不想将查询方法用作常规方法,而将其用作静态方法。所以我可以这样写代码:
Collection
就像我想我知道如何用Javascript编写。类似于:
let posts = Post.where("created", "<", new Date)
// but this should also still work:
let post = new Post("title", "body", new Date)
但是我不想写class PostShadow {
constructor(title, body, created) {
this.title = title
this.body = body
this.created = created
}
}
const Post = new Proxy(PostShadow, {
/* write my query-forwarding-code here */
})
类。我只想写PostShadow
或更好的class Post extends Model {}
,但是要以TypeScript理解@Model class Post {}
的类型定义的方式。到目前为止,我还没有找到如何使TypeScript理解这一点。
任何帮助将不胜感激。