my-test123
Version:
A planner front-end for Fabric8.
466 lines • 23.3 kB
JavaScript
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import { cloneDeep } from 'lodash';
import { HttpService } from '../services/http-service';
import { Injectable, ReflectiveInjector } from '@angular/core';
import { Response, ResponseOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import { Logger } from 'ngx-base';
import { MockDataService } from './mock-data.service';
/*
* This class provides a mock of the Angular 2 stock http service. It replaces
* the stock http service when the mock is used. Currently, the service is
* replaced 'manually'. When the Angular 2 API on the injectors are more stable,
* this class should be submitted to the Angular injector service to replace
* the http service on injection. Currently, this API is unstable and changes
* frequently, so we did not use it.
*
* How to extend the mock: when extending the mock service, you need to modify
* this class and add new behaviour to the http method functions below. Then you
* may need to extend the MockDataService to handle new entities and their storage.
* Actual mock data is placed in the mock generator classes to keep mock data
* seperated from logic. Note that the generators should only deal with initial data
* generation, not with persistence or logic.
*/
var MockHttp = /** @class */ (function (_super) {
__extends(MockHttp, _super);
function MockHttp(logger) {
var _this = _super.call(this, null, null, null) || this;
_this.logger = logger;
_this.UrlRegex = /app(\/.*)/g;
_this.WorkItemRegex = /workitems\/(.*)/g;
_this.WorkItemSearchRegexp = /work-item-list\/\?name=(.*)/g;
var injector = ReflectiveInjector.resolveAndCreate([MockDataService]);
_this.mockDataService = injector.get(MockDataService);
_this.selfId = _this.mockDataService.createId();
_this.logger.log('Started MockHttp service instance ' + _this.selfId);
return _this;
}
;
/*
* Parses the REST URL, returns a structure describing the base path, params
* and extra path values.
*/
MockHttp.prototype.parseURL = function (url) {
// TODO: when the url patterns get more complex, we should consider re-using
// some sort of REST URL parsing library to get a proper routing concept.
var a = document.createElement('a');
a.href = url;
var query = a.search.substr(1);
var params = {};
query.split('&').forEach(function (part) {
if (part) {
var item = part.split('=');
params[item[0]] = decodeURIComponent(item[1]);
}
});
// cut off first path element
var result = {
path: a['pathname'].replace(/^\/[^\/]+\//, '/'),
host: a['host'],
port: a['port'],
params: params
};
// parse extra paths based on resource
if (result.path.indexOf('/workitems/') == 0) {
result['extraPath'] = result.path.replace(/^\/workitems\//, '');
result['path'] = '/workitems';
}
if (result.path.indexOf('/workitemlinks/') == 0) {
result['extraPath'] = result.path.replace(/^\/workitemlinks\//, '');
result['path'] = '/workitemlinks';
}
if (result.path.indexOf('/workitemtypes/') == 0) {
result['extraPath'] = result.path.replace(/^\/workitemtypes\//, '');
result['path'] = '/workitemtypes';
}
if (result.path.indexOf('/user/') == 0) {
result['extraPath'] = result.path.replace(/^\/user\//, '');
result['path'] = '/user';
}
if (result.path.indexOf('/iterations/') == 0) {
result['extraPath'] = result.path.replace(/^\/iterations\//, '');
result['path'] = '/iterations';
}
if (result.path.indexOf('/areas/') == 0) {
result['extraPath'] = result.path.replace(/^\/areas\//, '');
result['path'] = '/areas';
}
if (result.path.indexOf('/comments/') == 0) {
result['extraPath'] = result.path.replace(/^\/comments\//, '');
result['path'] = '/comments';
}
if (result.path.indexOf('/workitemtypegroups/') == 0) {
result['extraPath'] = result.path.replace(/^\/workitemtypegroups\//, '');
result['path'] = '/workitemtypegroups';
}
// if request hat a /space prefix, note the space id, the re-parse the extra path
if (result.path.indexOf('/spacetemplates/') == 0) {
console.log('Space prefix detected, reparsing url..');
var spaceId = result.path.split('/')[2];
var newUrlBase = url.replace(/\/spacetemplates\/[^\/]+\//, '/');
console.log('Reparsing with url ' + newUrlBase);
// Recurse to parse sub-path
var newResult = this.parseURL(newUrlBase);
newResult.params['spaceId'] = spaceId;
result = newResult;
}
// if request hat a /space prefix, note the space id, the re-parse the extra path
if (result.path.indexOf('/spaces/') == 0) {
console.log('Space prefix detected, reparsing url..');
var spaceId = result.path.split('/')[2];
var newUrlBase = url.replace(/\/spaces\/[^\/]+\//, '/');
console.log('Reparsing with url ' + newUrlBase);
// Recurse to parse sub-path
var newResult = this.parseURL(newUrlBase);
newResult.params['spaceId'] = spaceId;
result = newResult;
}
if (result.path.indexOf('/iterations/') == 0) {
result['extraPath'] = result.path.replace(/^\/iterations\//, '');
result['path'] = '/iterations';
}
this.logger.log('Parsed request path: ' + JSON.stringify(result));
return result;
};
/*
* Creates and returns a http response structure wrapped in an Observable
* compatible with the stock http service return values. All results of the
* service must be wrapped in this envelope to be compatible with the
* stock http service API.
*/
MockHttp.prototype.createResponse = function (url, status, statusText, body) {
// future extension if needed: may also include headers:Headers
var responseOptions = new ResponseOptions({
url: url,
status: status,
statusText: statusText,
body: body
});
var res = new Response(responseOptions);
return Observable.of(res).delay(100);
};
/*
* Creates (slices) the requested paging set of a request. Takes the
* page parameters (offset, size) from the params and slices the
* work item set accordingly.
*/
MockHttp.prototype.createPage = function (workItems, params) {
this.logger.log('Workitems in filter = ' + workItems);
var offset = 0;
var limit = 20;
if (params['page[offset]'])
offset = parseInt(params['page[offset]']);
if (params['page[limit]'])
limit = params['page[limit]'];
this.logger.log('Creating paged workItems result: offset=' + offset + ' limit=' + limit);
var pageItems = workItems.slice(offset, limit);
var result = {
'data': pageItems,
'links': {
'first': 'http://mock.service/api/workitems?page[offset]=0&page[limit]=' + limit,
'last': 'http://mock.service/api/workitems?page[offset]=' + (workItems.length - limit) + '&page[limit]=' + limit,
'next': 'http://mock.service/api/workitems?page[offset]=' + (offset + limit) + '&page[limit]=' + limit
},
'meta': { 'totalCount': workItems.length }
};
//this.logger.log('Page result: ' + JSON.stringify(result));
return result;
};
/**
* Performs any type of http request. First argument is required, and can either be a url or
* a {@link Request} instance. If the first argument is a url, an optional {@link RequestOptions}
* object can be provided as the 2nd argument. The options object will be merged with the values
* of {@link BaseRequestOptions} before performing the request.
*/
MockHttp.prototype.request = function (url, options) {
if (typeof url === 'string')
return this.get(url, options);
else
this.logger.error('HTTP Requests with Request object arguments are not supported yet.');
return null;
};
;
/*
* Performs a request with 'get' http method.
*/
MockHttp.prototype.get = function (url, options) {
var path = this.parseURL(url);
if (path.path == null) {
this.logger.error('GET request failed with request url ' + url);
return this.createResponse(url.toString(), 500, 'error', {});
}
this.logger.log('GET request at ' + path.path + ' url=' + url.toString() + ' params=' + JSON.stringify(path.params));
if (path.extraPath) {
this.logger.log('GET request with extraPath at ' + path.extraPath + ' url= ' + url.toString() + ' params=' + path.params.toString());
}
// add new paths here
switch (path.path) {
case '/workitemtypes':
if (path.extraPath) {
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getWorkItemTypeById(path.extraPath) });
}
else {
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getWorkItemTypes() });
}
case '/workitems':
if (path.extraPath) {
return this.createResponse(url.toString(), 200, 'ok', this.mockDataService.getWorkItemOrEntity(path.extraPath));
}
else if (path.params['filter[assignee]'] || path.params['filter[workitemtype]'] || path.params['filter[state]'] || path.params['filter[iteration]'] || path.params['filter[area]'] || path.params['filter[creator]']) {
this.logger.log('Request contains filter expressions: ' + JSON.stringify(path.params));
return this.createResponse(url.toString(), 200, 'ok', this.createPage(this.mockDataService.getWorkItemsFiltered(path.params), path.params));
}
else {
return this.createResponse(url.toString(), 200, 'ok', this.createPage(this.mockDataService.getWorkItems(), path.params));
}
case '/user':
if (path.extraPath) {
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getUserById(path.extraPath) });
}
else {
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getUser() });
}
case '/users':
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getAllUsers() });
case '/collaborators':
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getAllUsers() });
case '/filters':
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getFilters() });
case '/work-item-list':
if (path.params['name']) {
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.searchWorkItem(path.params['name']) });
}
else {
return this.createResponse(url.toString(), 500, 'error: no search term given.', {});
}
case '/workitemlinks':
var workItemLinks = this.mockDataService.getWorkItemLinks();
return this.createResponse(url.toString(), 200, 'ok', { data: workItemLinks, 'meta': { 'totalCount': workItemLinks.length } });
case '/workitemlinktypes':
return this.createResponse(url.toString(), 200, 'ok', this.mockDataService.getWorkItemLinkTypes());
case '/workitemlinkcategories':
return this.createResponse(url.toString(), 500, 'not supported yet.', {});
case '/spaces':
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getAllSpaces(), links: {} });
case '/search':
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getWorkItems() });
case '/iterations':
if (path.extraPath) {
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getIteration(path.extraPath) });
}
else {
var iterations = this.mockDataService.getAllIterations();
return this.createResponse(url.toString(), 200, 'ok', { data: iterations, 'meta': { 'totalCount': iterations.length } });
}
case '/areas':
if (path.extraPath) {
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getArea(path.extraPath) });
}
else {
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getAllAreas() });
}
case '/workitemlinktypes':
return this.createResponse(url.toString(), 200, 'ok', this.mockDataService.getWorkItemLinkTypes());
case '/labels':
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getAllLabels() });
case '/workitemtypegroups':
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getAllGroupTypes() });
default:
console.log('######## URL Not found ########', url.toString());
return this.createResponse(url.toString(), 404, 'not found', {});
}
};
;
/*
* Performs a request with 'post' http method.
*/
MockHttp.prototype.post = function (url, body, options) {
this.logger.log('POST request at ' + url);
var path = this.parseURL(url);
if (path.path == null) {
this.logger.error('POST request failed with request url ' + url);
return this.createResponse(url.toString(), 500, 'error', {});
}
if (path.path === '/workitems') {
if (typeof body == 'string')
body = JSON.parse(body);
return this.createResponse(url.toString(), 200, 'ok', this.mockDataService.createWorkItemOrEntity(path.extraPath, body));
}
else if (path.path === '/iterations') {
if (typeof body == 'string')
body = JSON.parse(body);
var parentIterationId = null;
if (url.indexOf('iteration-id') != -1) {
// this is a create of a child iteration
parentIterationId = url.replace('http://mock.service/api/iterations/', '');
}
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.createIteration(body, parentIterationId) });
}
else if (path.path === '/workitemlinks') {
return this.createResponse(url.toString(), 200, 'ok', {
data: this.mockDataService.createWorkItemLink(JSON.parse(body).data),
included: this.mockDataService.createWorkItemLinkIncludes(JSON.parse(body).data)
});
}
else if (path.path === '/render') {
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.getRedneredText(JSON.parse(body).data) });
}
else if (path.path === '/login/refresh') {
return this.createResponse(url.toString(), 200, 'ok', { token: { access_token: 'someaccesstoken', refresh_token: 'someaccesstoken' } });
}
else if (path.path === '/labels') {
return this.createResponse(url.toString(), 200, 'ok', { data: this.mockDataService.createLabel(body) });
}
else {
return this.createResponse(url.toString(), 500, 'POST to unknown resource: ' + path.path, {});
}
};
;
/*
* Performs a request with 'put' http method.
*/
MockHttp.prototype.put = function (url, body, options) {
this.logger.log('PUT request at ' + url);
var path = this.parseURL(url);
if (path.path == null) {
this.logger.error('PUT request failed with request url ' + url);
return this.createResponse(url.toString(), 500, 'error', {});
}
if (path.path === '/workitems' && path.extraPath) {
var result = this.mockDataService.updateWorkItem(JSON.parse(body));
if (result != null)
return this.createResponse(url.toString(), 200, 'ok', { data: result });
else
return this.createResponse(url.toString(), 500, 'WorkItem does not exist: ' + path.extraPath, {});
}
else if (path.path === '/workitemlinks' && path.extraPath != null) {
var result = this.mockDataService.updateWorkItemLink(JSON.parse(body));
if (result != null)
return this.createResponse(url.toString(), 200, 'ok', result);
else
return this.createResponse(url.toString(), 500, 'WorkItemLink does not exist: ' + path.extraPath, {});
}
else
return this.createResponse(url.toString(), 500, 'PUT to unknown resource: ' + path.extraPath, {});
};
;
/*
* Performs a request with 'delete' http method.
*/
MockHttp.prototype.delete = function (url, options) {
this.logger.log('DELETE request at ' + url);
var path = this.parseURL(url);
if (path.path == null) {
this.logger.error('DELETE request failed with request url ' + url);
return this.createResponse(url.toString(), 500, 'error', {});
}
if (path.path === '/workitems' && path.extraPath) {
if (this.mockDataService.deleteWorkItem(path.extraPath))
return this.createResponse(url.toString(), 200, 'ok', {});
else
return this.createResponse(url.toString(), 500, 'WorkItem does not exist: ' + path.extraPath, {});
}
else if (path.path === '/iterations' && path.extraPath) {
if (this.mockDataService.deleteIteration(path.extraPath))
return this.createResponse(url.toString(), 200, 'ok', {});
else
return this.createResponse(url.toString(), 500, 'Iteration does not exist: ' + path.extraPath, {});
}
else if (path.path === '/workitemlinks' && path.extraPath) {
if (this.mockDataService.deleteWorkItemLink(path.extraPath))
return this.createResponse(url.toString(), 200, 'ok', {});
else
return this.createResponse(url.toString(), 500, 'WorkItemLink does not exist: ' + path.extraPath, {});
}
else if (path.path === '/comments' && path.extraPath) {
if (this.mockDataService.deleteComment(path.extraPath))
return this.createResponse(url.toString(), 200, 'ok', {});
else
return this.createResponse(url.toString(), 500, 'Comment does not exist: ' + path.extraPath, {});
}
};
;
/*
* Performs a request with 'patch' http method.
*/
MockHttp.prototype.patch = function (url, body, options) {
// Note: this assumes the PATCH request contains the full entity in the body!
this.logger.log('PATCH request at ' + url);
var path = this.parseURL(url);
if (path.path == null) {
this.logger.error('PATCH request failed with request url ' + url);
return this.createResponse(url.toString(), 500, 'error', {});
}
if (path.path === '/workitems' && path.extraPath) {
if (path.extraPath === 'reorder') {
var result = JSON.parse(body).data;
}
else {
var result = this.mockDataService.updateWorkItem(JSON.parse(body).data);
}
if (result != null)
return this.createResponse(url.toString(), 200, 'ok', { data: result });
else
return this.createResponse(url.toString(), 500, 'WorkItem does not exist: ' + path.extraPath, {});
}
else if (path.path === '/workitemlinks' && path.extraPath != null) {
var result = this.mockDataService.updateWorkItemLink(JSON.parse(body));
if (result != null)
return this.createResponse(url.toString(), 200, 'ok', result);
else
return this.createResponse(url.toString(), 500, 'WorkItemLink does not exist: ' + path.extraPath, {});
}
else if (path.path === '/iterations' && path.extraPath != null) {
var result = this.mockDataService.updateIteration(body);
if (result != null)
return this.createResponse(url.toString(), 200, 'ok', { data: result });
else
return this.createResponse(url.toString(), 500, 'Iteration does not exist: ' + path.extraPath, {});
}
else if (path.path.includes('/comments/')) {
var resp = cloneDeep(body.data);
resp.attributes['body.rendered'] = resp.attributes['body'];
return this.createResponse(url.toString(), 200, 'ok', { data: resp });
}
else {
return this.createResponse(url.toString(), 500, 'PATCH to unknown resource: ' + path.extraPath, {});
}
};
;
/*
* Performs a request with 'head' http method.
*/
MockHttp.prototype.head = function (url, options) {
this.logger.log('HEAD request at ' + url);
return this.createResponse(url.toString(), 500, 'PATCH method not implemented in mock-http.', {});
};
;
/*
* Performs a request with 'options' http method.
*/
MockHttp.prototype.options = function (url, options) {
this.logger.log('OPTIONS request at ' + url);
return this.createResponse(url.toString(), 500, 'PATCH method not implemented in mock-http.', {});
};
;
MockHttp.decorators = [
{ type: Injectable },
];
/** @nocollapse */
MockHttp.ctorParameters = function () { return [
{ type: Logger, },
]; };
return MockHttp;
}(HttpService));
export { MockHttp };
//# sourceMappingURL=mock-http.js.map