Skip to content

Commit

Permalink
Merge pull request #2 from Exilz/dev
Browse files Browse the repository at this point in the history
v1.0.1
  • Loading branch information
Exilz authored Aug 23, 2017
2 parents 83685a5 + 16d5c69 commit 638ea8e
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 35 deletions.
37 changes: 29 additions & 8 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ var OfflineFirstAPI = (function () {
}
OfflineFirstAPI.prototype.fetch = function (service, options) {
return __awaiter(this, void 0, void 0, function () {
var serviceDefinition, fullPath, middlewares, fetchOptions, fetchHeaders, shouldCache, requestId, expiration, _sha, expirationDelay, cachedData, parsedResponseData, res, err_1;
var serviceDefinition, fullPath, middlewares, fetchOptions, fetchHeaders, shouldUseCache, requestId, expiration, _sha, expirationDelay, cachedData, parsedResponseData, res, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
Expand All @@ -89,8 +89,7 @@ var OfflineFirstAPI = (function () {
middlewares = _a.sent();
fetchOptions = _merge(middlewares, (options && options.fetchOptions) || {}, { method: serviceDefinition.method }, { headers: (options && options.headers) || {} });
fetchHeaders = options && options.fetchHeaders;
shouldCache = !this._APIOptions.disableCache &&
!(serviceDefinition.disableCache || (options && options.disableCache));
shouldUseCache = this._shouldUseCache(serviceDefinition, options);
requestId = void 0;
expiration = void 0;
_sha = new sha('SHA-1', 'TEXT');
Expand All @@ -101,12 +100,12 @@ var OfflineFirstAPI = (function () {
return [4 /*yield*/, this._getCachedData(service, requestId, fullPath)];
case 3:
cachedData = _a.sent();
if (cachedData.success && cachedData.fresh) {
if (cachedData.success && cachedData.fresh && shouldUseCache) {
this._log("Using fresh cache for " + fullPath);
return [2 /*return*/, cachedData.data];
}
// Network fetch
this._logNetwork(serviceDefinition, fetchHeaders, options);
this._logNetwork(serviceDefinition, fullPath, fetchHeaders, options);
this._log('full URL for request', fullPath);
this._log('full fetch options for request', fetchOptions);
parsedResponseData = void 0;
Expand All @@ -133,7 +132,7 @@ var OfflineFirstAPI = (function () {
_a.label = 7;
case 7:
// Cache if it hasn't been disabled and if the network request has been successful
if (res.data.ok && shouldCache) {
if (res.data.ok && shouldUseCache) {
this._cache(service, requestId, parsedResponseData, expiration);
}
this._log('parsed network response', parsedResponseData);
Expand Down Expand Up @@ -344,6 +343,28 @@ var OfflineFirstAPI = (function () {
});
});
};
/**
* Helper returning if caching should be enabled for a request.
* Cache enabling priority :
* option parameter of fetch() > service definition > default setting
* @private
* @param {IAPIService} serviceDefinition
* @param {IFetchOptions} options
* @returns {boolean}
* @memberof OfflineFirstAPI
*/
OfflineFirstAPI.prototype._shouldUseCache = function (serviceDefinition, options) {
var cacheDisabledFromOptions = options && options.disableCache;
if (typeof cacheDisabledFromOptions !== 'undefined') {
return !cacheDisabledFromOptions;
}
else if (typeof serviceDefinition.disableCache !== 'undefined') {
return !serviceDefinition.disableCache;
}
else {
return !this._APIOptions.disableCache;
}
};
/**
* Pushes a requestId into a service's dictionary and associate its expiration date to it.
* @private
Expand Down Expand Up @@ -558,9 +579,9 @@ var OfflineFirstAPI = (function () {
* @param {IFetchOptions} [options]
* @memberof OfflineFirstAPI
*/
OfflineFirstAPI.prototype._logNetwork = function (serviceDefinition, fetchHeaders, options) {
OfflineFirstAPI.prototype._logNetwork = function (serviceDefinition, fullPath, fetchHeaders, options) {
if (this._APIOptions.printNetworkRequests) {
console.log("%c Network request " + (fetchHeaders ? '(headers only)' : '') + " for " + serviceDefinition.path + " " +
console.log("%c Network request " + (fetchHeaders ? '(headers only)' : '') + " for " + fullPath + " " +
("(" + ((options && options.method) || serviceDefinition.method) + ")"), 'font-weight: bold; color: blue');
}
};
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-native-offline-api",
"version": "1.0.0",
"version": "1.0.1",
"description": "Offline first API wrapper for react-native",
"main": "./dist/index.js",
"types": "./src/index.d.ts",
Expand Down
49 changes: 27 additions & 22 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,7 @@ export default class OfflineFirstAPI {
{ headers: (options && options.headers) || {} }
);
const fetchHeaders = options && options.fetchHeaders;
// Should be cached if : not disabled globally, not disabled for this service definition and not
// disabled from the option parameter of fetch ()
const shouldCache = !this._APIOptions.disableCache &&
!(serviceDefinition.disableCache || (options && options.disableCache));
const shouldUseCache = this._shouldUseCache(serviceDefinition, options);
let requestId;
let expiration;

Expand All @@ -77,13 +74,13 @@ export default class OfflineFirstAPI {
expiration = Date.now() + expirationDelay;
const cachedData = await this._getCachedData(service, requestId, fullPath);

if (cachedData.success && cachedData.fresh) {
if (cachedData.success && cachedData.fresh && shouldUseCache) {
this._log(`Using fresh cache for ${fullPath}`);
return cachedData.data;
}

// Network fetch
this._logNetwork(serviceDefinition, fetchHeaders, options);
this._logNetwork(serviceDefinition, fullPath, fetchHeaders, options);
this._log('full URL for request', fullPath);
this._log('full fetch options for request', fetchOptions);
let parsedResponseData;
Expand All @@ -107,7 +104,7 @@ export default class OfflineFirstAPI {
}

// Cache if it hasn't been disabled and if the network request has been successful
if (res.data.ok && shouldCache) {
if (res.data.ok && shouldUseCache) {
this._cache(service, requestId, parsedResponseData, expiration);
}

Expand Down Expand Up @@ -174,7 +171,6 @@ export default class OfflineFirstAPI {
this._log('custom driver set');
}


/**
* Simple helper that won't ever throw an error into the stack if the network request
* isn't successful. This is useful to implement the cache's logic when the API is unreachable.
Expand All @@ -192,7 +188,6 @@ export default class OfflineFirstAPI {
}
}


/**
* Cache the network response for a request. Create the service dictionary if it hasn't been done yet,
* store the expiration date to the requestId and finally store the data itself.
Expand All @@ -216,7 +211,6 @@ export default class OfflineFirstAPI {
}
}


/**
* Promise that tries to fetch a cached data. Resolves the data if successful and its freshness.
* If this request hasn't been cached yet, resolves with success set to false.
Expand Down Expand Up @@ -253,6 +247,27 @@ export default class OfflineFirstAPI {
}


/**
* Helper returning if caching should be enabled for a request.
* Cache enabling priority :
* option parameter of fetch() > service definition > default setting
* @private
* @param {IAPIService} serviceDefinition
* @param {IFetchOptions} options
* @returns {boolean}
* @memberof OfflineFirstAPI
*/
private _shouldUseCache (serviceDefinition: IAPIService, options: IFetchOptions): boolean {
const cacheDisabledFromOptions = options && options.disableCache;
if (typeof cacheDisabledFromOptions !== 'undefined') {
return !cacheDisabledFromOptions;
} else if (typeof serviceDefinition.disableCache !== 'undefined') {
return !serviceDefinition.disableCache;
} else {
return !this._APIOptions.disableCache;
}
}

/**
* Pushes a requestId into a service's dictionary and associate its expiration date to it.
* @private
Expand All @@ -279,7 +294,6 @@ export default class OfflineFirstAPI {
}
}


/**
* Promise that resolves every cache key associated to a service : the service dictionary's name, and all requestId
* stored. This is useful to clear the cache without affecting the user's stored data not related to this API.
Expand All @@ -305,7 +319,6 @@ export default class OfflineFirstAPI {
}
}


/**
* Simple helper getting a service's dictionary cache key.
* @private
Expand All @@ -317,7 +330,6 @@ export default class OfflineFirstAPI {
return `${CACHE_PREFIX}:dictionary:${service}`;
}


/**
* Simple helper getting a request's cache key.
* @private
Expand All @@ -329,7 +341,6 @@ export default class OfflineFirstAPI {
return `${CACHE_PREFIX}:${requestId}`;
}


/**
* Resolve each middleware provided and merge them into a single object that will be passed to
* the network request.
Expand All @@ -355,7 +366,6 @@ export default class OfflineFirstAPI {
}
}


/**
* Helper returning the full URL of a service and its options.
* @private
Expand All @@ -374,7 +384,6 @@ export default class OfflineFirstAPI {
return domainURL + prefix + '/' + parsedPath;
}


/**
* Helper replacing the pathParameters from the service definition's path and appending
* any supplied query parameters. For instance :
Expand Down Expand Up @@ -408,7 +417,6 @@ export default class OfflineFirstAPI {
return path;
}


/**
* Merge the supplied API options with the default ones.
* @private
Expand All @@ -427,7 +435,6 @@ export default class OfflineFirstAPI {
};
}


/**
* For each suppliedservice, map the default service options to it and throw errors if the required
* options are missing.
Expand Down Expand Up @@ -457,7 +464,6 @@ export default class OfflineFirstAPI {
});
}


/**
* Debug helper logging every network request.
* @private
Expand All @@ -466,17 +472,16 @@ export default class OfflineFirstAPI {
* @param {IFetchOptions} [options]
* @memberof OfflineFirstAPI
*/
private _logNetwork (serviceDefinition: IAPIService, fetchHeaders: boolean, options?: IFetchOptions): void {
private _logNetwork (serviceDefinition: IAPIService, fullPath: string, fetchHeaders: boolean, options?: IFetchOptions): void {
if (this._APIOptions.printNetworkRequests) {
console.log(
`%c Network request ${fetchHeaders ? '(headers only)' : ''} for ${serviceDefinition.path} ` +
`%c Network request ${fetchHeaders ? '(headers only)' : ''} for ${fullPath} ` +
`(${(options && options.method) || serviceDefinition.method})`,
'font-weight: bold; color: blue'
);
}
}


/**
* Debug helper logging every major logic step when user has enabled debugging.
* @private
Expand Down
5 changes: 1 addition & 4 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@
"sourceMap": false,
"alwaysStrict": true,
"strictNullChecks": false,
"noUnusedLocals": false,
"types": [
"src/index.d.ts"
]
"noUnusedLocals": false
},
"include": [
"src"
Expand Down

0 comments on commit 638ea8e

Please sign in to comment.