Created
August 1, 2019 01:33
-
-
Save el-ethan/32bec8dec2f3ab31009ce06c24370fa7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* To use JSON Server to serve API responses you will need to do the following: | |
* 1. create a db.json. | |
* 2. In your browser, set the following local storage key-value pairs: | |
* a) set use-json-server to true (unquoted). This will tell Angular to route your API requests to JSON Server. | |
* b) (optional) set json-server-blacklist to an array of double quoted string urls starting with slashes. | |
* This will tell Angular which urls (if any) to serve with the web server. | |
* @example | |
* ["/my-special-endpoint", "/my/resource"] | |
*/ | |
angular.module('JSONServerInterceptor', []).config(['$httpProvider', function($httpProvider) { | |
if (window.localStorage.getItem('use-json-server') === 'true') { | |
const blacklist = window.localStorage.getItem('json-server-blacklist'); | |
const JSONServerBlacklist = blacklist ? JSON.parse(blacklist) : []; | |
const JSON_SERVER_HOST = 'http://localhost:3000'; | |
const extraMessage = JSONServerBlacklist.length > 0 ? `except for the following: ${JSONServerBlacklist.join(', ')}` : ''; | |
console.warn( | |
`WARNING: you are using JSON server. All requests are being routed to ${JSON_SERVER_HOST} \n${extraMessage}` | |
); | |
$httpProvider.interceptors.push(['$q', function($q) { | |
return { | |
request: function (config) { | |
const url = config.url; | |
// ignore requests for htm and html files, and request from the blacklist | |
if (url.includes('.htm') || JSONServerBlacklist.includes(url)) { | |
return config || $q.when(config); | |
} | |
config.url = JSON_SERVER_HOST + config.url; | |
return config || $q.when(config); | |
} | |
}; | |
}]); | |
} | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment