| 88 | } |
| 89 | |
| 90 | public async create(attributes: Required<ValidAttributes>): Promise<Model> { |
| 91 | return this.database.sequence(async (sequenceDb: DatabaseInterface): Promise<Model> => { |
| 92 | const entries = Object.entries(attributes); |
| 93 | const fields = entries.map(([key, _]: [string, any]) => sql`${new QueryIdentifier(key)}`); |
| 94 | const values = entries.map(([_, val]: [string, any]) => sql`${val}`); |
| 95 | |
| 96 | const data = (await sequenceDb.insertAndGet(sql` |
| 97 | INSERT INTO ${new QueryIdentifier(this.table)} (${SqlQuery.join(fields, sql`, `)}) |
| 98 | VALUES (${SqlQuery.join(values, sql`, `)}) |
| 99 | `))[0]; |
| 100 | |
| 101 | if (typeof data === 'string' || typeof data === 'number') { |
| 102 | const results = await sequenceDb.query(sql` |
| 103 | SELECT * |
| 104 | FROM ${new QueryIdentifier(this.table)} |
| 105 | WHERE ${new QueryIdentifier(this.primaryKey)} = ${data}; |
| 106 | `); |
| 107 | |
| 108 | if (results.length === 0) { |
| 109 | throw new NotFoundError(`Object not found in table ${this.table} after insert (got ${this.primaryKey} = ${data})`); |
| 110 | } |
| 111 | |
| 112 | return this.createModelFromAttributes(results[0]); |
| 113 | } else { |
| 114 | return this.createModelFromAttributes(data); |
| 115 | } |
| 116 | }); |
| 117 | } |
| 118 | |
| 119 | public async update(model: Model, attributes: Partial<ValidAttributes>): Promise<Model> { |
| 120 | return this.database.sequence(async (sequenceDb: DatabaseInterface): Promise<Model> => { |