Browse Source

Optimize database cache implementation

pull/6/head
Menci 6 years ago
parent
commit
804e9689db
  1. 16
      models/common.ts

16
models/common.ts

@ -49,27 +49,27 @@ export default class Model extends TypeORM.BaseEntity {
const doQuery = async () => await (this as any).findOne(parseInt(id as any) || 0); const doQuery = async () => await (this as any).findOne(parseInt(id as any) || 0);
if ((this as typeof Model).cache) { if ((this as typeof Model).cache) {
let result; const resultObject = cacheGet(this.name, id);
if (result = cacheGet(this.name, id)) { if (resultObject) {
return result.clone(); return (this as typeof Model).create(resultObject) as any as T;
} }
result = await doQuery(); const result = await doQuery();
if (result) { if (result) {
cacheSet(this.name, id, result); cacheSet(this.name, id, result.toPlain());
} }
return result && result.clone(); return result;
} else { } else {
return await doQuery(); return await doQuery();
} }
} }
clone() { toPlain() {
const object = {}; const object = {};
TypeORM.getConnection().getMetadata(this.constructor).ownColumns.map(column => column.propertyName).forEach(key => { TypeORM.getConnection().getMetadata(this.constructor).ownColumns.map(column => column.propertyName).forEach(key => {
object[key] = DeepCopy(this[key]); object[key] = DeepCopy(this[key]);
}); });
return (this.constructor as any).create(object); return object;
} }
async destroy() { async destroy() {

Loading…
Cancel
Save