|
| 1 | + |
| 2 | +import MongoCollection from './MongoCollection'; |
| 3 | + |
| 4 | +function _mongoSchemaQueryFromNameQuery(name: string, query) { |
| 5 | + return _mongoSchemaObjectFromNameFields(name, query); |
| 6 | +} |
| 7 | + |
| 8 | +function _mongoSchemaObjectFromNameFields(name: string, fields) { |
| 9 | + let object = { _id: name }; |
| 10 | + if (fields) { |
| 11 | + Object.keys(fields).forEach(key => { |
| 12 | + object[key] = fields[key]; |
| 13 | + }); |
| 14 | + } |
| 15 | + return object; |
| 16 | +} |
| 17 | + |
| 18 | +export default class MongoSchemaCollection { |
| 19 | + _collection: MongoCollection; |
| 20 | + |
| 21 | + constructor(collection: MongoCollection) { |
| 22 | + this._collection = collection; |
| 23 | + } |
| 24 | + |
| 25 | + getAllSchemas() { |
| 26 | + return this._collection._rawFind({}); |
| 27 | + } |
| 28 | + |
| 29 | + findSchema(name: string) { |
| 30 | + return this._collection._rawFind(_mongoSchemaQueryFromNameQuery(name), { limit: 1 }).then(results => { |
| 31 | + return results[0]; |
| 32 | + }); |
| 33 | + } |
| 34 | + |
| 35 | + // Atomically find and delete an object based on query. |
| 36 | + // The result is the promise with an object that was in the database before deleting. |
| 37 | + // Postgres Note: Translates directly to `DELETE * FROM ... RETURNING *`, which will return data after delete is done. |
| 38 | + findAndDeleteSchema(name: string) { |
| 39 | + // arguments: query, sort |
| 40 | + return this._collection._mongoCollection.findAndRemove(_mongoSchemaQueryFromNameQuery(name), []).then(document => { |
| 41 | + // Value is the object where mongo returns multiple fields. |
| 42 | + return document.value; |
| 43 | + }); |
| 44 | + } |
| 45 | + |
| 46 | + addSchema(name: string, fields) { |
| 47 | + let mongoObject = _mongoSchemaObjectFromNameFields(name, fields); |
| 48 | + return this._collection.insertOne(mongoObject); |
| 49 | + } |
| 50 | + |
| 51 | + updateSchema(name: string, update) { |
| 52 | + return this._collection.updateOne(_mongoSchemaQueryFromNameQuery(name), update); |
| 53 | + } |
| 54 | + |
| 55 | + upsertSchema(name: string, query: string, update) { |
| 56 | + return this._collection.upsertOne(_mongoSchemaQueryFromNameQuery(name, query), update); |
| 57 | + } |
| 58 | +} |
0 commit comments