Skip to content

Commit

Permalink
✨ Support multiple cache objects
Browse files Browse the repository at this point in the history
  • Loading branch information
zswang committed Jun 29, 2018
1 parent 4ff96a5 commit 74a445b
Show file tree
Hide file tree
Showing 6 changed files with 242 additions and 83 deletions.
31 changes: 28 additions & 3 deletions lib/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export interface ICacheOptions<T> {
* 获取数据的方法
*/
fetch: {
(): Promise<T>;
(key?: string | number): Promise<T>;
};
}
export declare class Cache<T> {
Expand Down Expand Up @@ -161,13 +161,38 @@ export declare class Cache<T> {
cache5.fetch().catch(err => {
console.log(err)
// > cache5 error
})
```
* @example fetch():key
```js
let cache6 = new jfetchs.Cache({
debug: true,
fetch: key => {
if (key === 6) {
return Promise.resolve(666)
}
return Promise.reject(`cache6 ${key} error`)
},
})
cache6.fetch('ok').catch(err => {
console.log(err)
// > cache6 ok error
})
cache6.fetch(3).catch(err => {
console.log(err)
// > cache6 3 error
})
cache6.flush(3)
cache6.fetch(6).then(data => {
console.log(data)
// > 666
})
```
*/
fetch(): Promise<T>;
fetch(key?: string | number): Promise<T>;
/**
* 移除缓存
*/
flush(): void;
flush(key?: string | number): void;
}
//# sourceMappingURL=index.d.ts.map
85 changes: 61 additions & 24 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,16 @@ var __assign = (this && this.__assign) || Object.assign || function(t) {
Object.defineProperty(exports, "__esModule", { value: true });
var Cache = /** @class */ (function () {
function Cache(options) {
this.fetchedAt = 0;
this.fetchedAt = {};
this.fetchData = {};
/**
* 获取数据中
*/
this.fetching = {};
/**
* 读取队列2
*/
this.queue = [];
this.queue = {};
this.options = __assign({ debug: false, expire: 60 * 60 }, options);
}
/**
Expand Down Expand Up @@ -162,54 +167,85 @@ var __assign = (this && this.__assign) || Object.assign || function(t) {
cache5.fetch().catch(err => {
console.log(err)
// > cache5 error
})
```
* @example fetch():key
```js
let cache6 = new jfetchs.Cache({
debug: true,
fetch: key => {
if (key === 6) {
return Promise.resolve(666)
}
return Promise.reject(`cache6 ${key} error`)
},
})
cache6.fetch('ok').catch(err => {
console.log(err)
// > cache6 ok error
})
cache6.fetch(3).catch(err => {
console.log(err)
// > cache6 3 error
})
cache6.flush(3)
cache6.fetch(6).then(data => {
console.log(data)
// > 666
})
```
*/
Cache.prototype.fetch = function () {
Cache.prototype.fetch = function (key) {
var _this = this;
if (key === void 0) { key = ''; }
var now = Date.now();
var prefix = typeof this.options.debug === 'string'
? ' ' + JSON.stringify(this.options.debug)
: '';
if (now - this.fetchedAt <= this.options.expire * 1000) {
if (now - (this.fetchedAt[key] || 0) <= this.options.expire * 1000) {
if (this.options.debug) {
console.log("jfetchs/src/index.ts:69" + prefix + " hitting cache");
console.log("jfetchs/src/index.ts:75" + prefix + " hitting cache");
}
return Promise.resolve(this.fetchData);
return Promise.resolve(this.fetchData[key]);
}
if (this.fetching) {
if (this.fetching[key]) {
if (this.options.debug) {
console.log("jfetchs/src/index.ts:76" + prefix + " fetching in queue");
console.log("jfetchs/src/index.ts:82" + prefix + " fetching in queue");
}
return new Promise(function (resolve, reject) {
_this.queue.push({
_this.queue[key] = _this.queue[key] || [];
_this.queue[key].push({
resolve: resolve,
reject: reject,
});
});
}
if (this.options.debug) {
console.log("jfetchs/src/index.ts:87" + prefix + " missing cache");
console.log("jfetchs/src/index.ts:94" + prefix + " missing cache");
}
this.flush();
this.fetching = true;
this.fetching[key] = true;
return new Promise(function (resolve, reject) {
_this.options
.fetch()
.fetch(key)
.then(function (data) {
_this.fetchData = data;
_this.fetchedAt = now;
_this.fetching = false;
var item;
while ((item = _this.queue.shift())) {
item.resolve(data);
_this.fetchData[key] = data;
_this.fetchedAt[key] = now;
_this.fetching[key] = false;
if (_this.queue[key]) {
var item = void 0;
while ((item = _this.queue[key].shift())) {
item.resolve(data);
}
}
resolve(data);
})
.catch(function (err) {
var item;
while ((item = _this.queue.shift())) {
item.reject(err);
if (_this.queue[key]) {
var item = void 0;
while ((item = _this.queue[key].shift())) {
item.reject(err);
}
}
reject(err);
});
Expand All @@ -218,9 +254,10 @@ var __assign = (this && this.__assign) || Object.assign || function(t) {
/**
* 移除缓存
*/
Cache.prototype.flush = function () {
this.fetchData = null;
this.fetchedAt = 0;
Cache.prototype.flush = function (key) {
if (key === void 0) { key = ''; }
this.fetchData[key] = null;
this.fetchedAt[key] = 0;
};
return Cache;
}());
Expand Down
90 changes: 61 additions & 29 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,26 @@ export interface ICacheOptions<T> {
* 获取数据的方法
*/
fetch: {
(): Promise<T>
(key?: string | number): Promise<T>
}
}
export class Cache<T> {
private options: ICacheOptions<T>
private fetchedAt: number = 0
private fetchData: T
private fetchedAt: { [key: string]: number } = {}
private fetchData: { [key: string]: T } = {}
/**
* 获取数据中
*/
private fetching: boolean
private fetching: { [key: string]: boolean } = {}
/**
* 读取队列2
*/
private queue: {
resolve: Function
reject: Function
}[] = []
[key: string]: {
resolve: Function
reject: Function
}[]
} = {}
constructor(options: ICacheOptions<T>) {
this.options = {
debug: false,
Expand Down Expand Up @@ -170,54 +172,84 @@ cache5.fetch().catch(err => {
cache5.fetch().catch(err => {
console.log(err)
// > cache5 error
})
```
* @example fetch():key
```js
let cache6 = new jfetchs.Cache({
debug: true,
fetch: key => {
if (key === 6) {
return Promise.resolve(666)
}
return Promise.reject(`cache6 ${key} error`)
},
})
cache6.fetch('ok').catch(err => {
console.log(err)
// > cache6 ok error
})
cache6.fetch(3).catch(err => {
console.log(err)
// > cache6 3 error
})
cache6.flush(3)
cache6.fetch(6).then(data => {
console.log(data)
// > 666
})
```
*/
fetch(): Promise<T> {
fetch(key: string | number = ''): Promise<T> {
const now = Date.now()
const prefix =
typeof this.options.debug === 'string'
? ' ' + JSON.stringify(this.options.debug)
: ''
if (now - this.fetchedAt <= this.options.expire * 1000) {
if (now - (this.fetchedAt[key] || 0) <= this.options.expire * 1000) {
if (this.options.debug) {
console.log(`jfetchs/src/index.ts:69${prefix} hitting cache`)
console.log(`jfetchs/src/index.ts:75${prefix} hitting cache`)
}
return Promise.resolve(this.fetchData)
return Promise.resolve(this.fetchData[key])
}
if (this.fetching) {
if (this.fetching[key]) {
if (this.options.debug) {
console.log(`jfetchs/src/index.ts:76${prefix} fetching in queue`)
console.log(`jfetchs/src/index.ts:82${prefix} fetching in queue`)
}
return new Promise((resolve, reject) => {
this.queue.push({
this.queue[key] = this.queue[key] || []
this.queue[key].push({
resolve: resolve,
reject: reject,
})
})
}
if (this.options.debug) {
console.log(`jfetchs/src/index.ts:87${prefix} missing cache`)
console.log(`jfetchs/src/index.ts:94${prefix} missing cache`)
}
this.flush()
this.fetching = true
this.fetching[key] = true
return new Promise((resolve, reject) => {
this.options
.fetch()
.fetch(key)
.then(data => {
this.fetchData = data
this.fetchedAt = now
this.fetching = false
let item
while ((item = this.queue.shift())) {
item.resolve(data)
this.fetchData[key] = data
this.fetchedAt[key] = now
this.fetching[key] = false
if (this.queue[key]) {
let item
while ((item = this.queue[key].shift())) {
item.resolve(data)
}
}
resolve(data)
})
.catch(err => {
let item
while ((item = this.queue.shift())) {
item.reject(err)
if (this.queue[key]) {
let item
while ((item = this.queue[key].shift())) {
item.reject(err)
}
}
reject(err)
})
Expand All @@ -226,8 +258,8 @@ cache5.fetch().catch(err => {
/**
* 移除缓存
*/
flush() {
this.fetchData = null
this.fetchedAt = 0
flush(key: string | number = '') {
this.fetchData[key] = null
this.fetchedAt[key] = 0
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "jfetchs",
"version": "0.0.13",
"version": "0.1.0",
"description": "Cache of fetch data",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
Expand Down
Loading

0 comments on commit 74a445b

Please sign in to comment.