|
1 | 1 | import { firestore as __firestore } from "firebase-admin";
|
2 |
| -import { KeyValueStore } from "src/SchemaTypes/Object/types/KeyValue"; |
| 2 | +import Document from "../Document/class"; |
| 3 | +import { KeyValueStore } from "../SchemaTypes/Object/types/KeyValue"; |
3 | 4 | import ObjectSchema from "../SchemaTypes/Object/class";
|
| 5 | +import { ModelErrorTypes as ErrorType } from "./types/error"; |
| 6 | +import makeError from "../utils/makeError"; |
4 | 7 |
|
5 | 8 | class Model<T extends KeyValueStore = any> {
|
| 9 | + private __name: string; |
| 10 | + |
| 11 | + private __schema: ObjectSchema<T>; |
| 12 | + |
| 13 | + private __db: __firestore.Firestore; |
| 14 | + |
6 | 15 | constructor(
|
7 |
| - private __name: string, |
8 |
| - private __schema: ObjectSchema<T>, |
9 |
| - private __db: __firestore.Firestore |
10 |
| - ) {} |
| 16 | + name: string, |
| 17 | + schema: ObjectSchema<T>, |
| 18 | + firestore: __firestore.Firestore |
| 19 | + ) { |
| 20 | + this.__name = name; |
| 21 | + this.__schema = schema; |
| 22 | + this.__db = firestore; |
| 23 | + } |
| 24 | + |
| 25 | + get name() { |
| 26 | + return this.__name; |
| 27 | + } |
| 28 | + |
| 29 | + get schema() { |
| 30 | + return this.__schema; |
| 31 | + } |
| 32 | + |
| 33 | + public create = async (data: Partial<T>) => { |
| 34 | + const { valid, value, errors } = this.__schema.validate(data); |
| 35 | + if (!valid) { |
| 36 | + throw makeError(ErrorType.validation, errors); |
| 37 | + } |
| 38 | + |
| 39 | + const docRef = await this.__db |
| 40 | + .collection(this.__name) |
| 41 | + .add(value) |
| 42 | + .catch((err: Error) => { |
| 43 | + throw makeError(ErrorType.firestore, err.message); |
| 44 | + }); |
11 | 45 |
|
12 |
| - public print = () => { |
13 |
| - console.log(this.__db, this.__name, this.__schema); |
| 46 | + return new Document<T>( |
| 47 | + docRef as __firestore.DocumentReference<T>, |
| 48 | + this.__name, |
| 49 | + this.__schema |
| 50 | + ); |
14 | 51 | };
|
15 | 52 | }
|
16 | 53 |
|
|
0 commit comments