consul/ui-v2/tests/helpers/api.js

44 lines
1.2 KiB
JavaScript
Raw Normal View History

import getAPI from '@hashicorp/ember-cli-api-double';
2018-05-11 12:47:21 +00:00
import setCookies from 'consul-ui/tests/helpers/set-cookies';
import typeToURL from 'consul-ui/tests/helpers/type-to-url';
Move testing doubles to use data embedded in the HTML vs HTTP/fetch Previously `api-double` usage in ember would require a bunch of `fetch` requests to pull in the 'api double', this had a number of disadvantages. 1. The doubles needed to be available via HTTP, which meant a short term solution of rsyncing the double files over to `public` in order to be served over HTTP. An alternative to that would have been figuring out how to serve something straight from `node_modules`, which would have been preferable. 2. ember/testem would not serve dot files (so anything starting with a ., like `.config`. To solve this via ember/testem would have involved digging in to understand how to enable the serving of dot files. 3. ember/testem automatically rewrote urls for non-existant files to folders, i.e. adding a slash for you, so `/v1/connect/intentions` would be rewritten to `/v1/connect/intentions/`. This is undesirable, and solving this via ember/testem would have involved digging deep to disable that. Serving the files via HTTP has now changed. The double files are now embedded into the HTML has 'embedded templates' that can be found by using the url of the file and a simple `querySelector`. This of course only happens during testing and means I can fully control the 'serving' of the doubles now, so I can say goodbye to the need to move files around, worry about the need to serve dotfiles and the undesirable trailing slashes rewriting. Winner! Find the files and embedding them is done using a straightforward recursive-readdir-sync (the `content-for` functionality is a synchronous api) as oppose to getting stuck into `broccoli`.
2018-07-02 18:02:16 +00:00
import config from 'consul-ui/config/environment';
const apiConfig = config['ember-cli-api-double'];
let path = '/consul-api-double';
let reader;
if (apiConfig) {
const temp = apiConfig.endpoints[0].split('/');
reader = apiConfig.reader;
temp.pop();
path = temp.join('/');
}
const api = getAPI(path, setCookies, typeToURL, reader);
export const get = function(_url, options = { headers: { cookie: {} } }) {
const url = new URL(_url, 'http://localhost');
return new Promise(function(resolve) {
return api.api.serve(
{
method: 'GET',
path: url.pathname,
url: url.href,
cookies: options.headers.cookie || {},
headers: {},
query: [...url.searchParams.keys()].reduce(function(prev, key) {
prev[key] = url.searchParams.get(key);
return prev;
}, {}),
},
{
set: function() {},
status: function() {
return this;
},
send: function(content) {
resolve(JSON.parse(content));
},
},
function() {}
);
});
};
export default api;