[AAE-12501] Align JS API (#8344)

* [AAE-12501] Provide an AlfrescoApiService implementation that disable the AlfrescoApi oauth initialization when we use new oidc implementation

* [AAE-12501] Replace oauth2Auth with authentication service, define get username as abstract

* [AAE-12501] Replace sitesService with authentication service since sitesService get the username from oauth2Auth

* [AAE-12501] Call implicitLogin by authentication service

* [AAE-12501] Replace Oauth2Auth with AlfrescoApi and call the custom api without using authentication

* [AAE-12501] Replace oauth2Auth with authentication service to get the token

* [AAE-12501] Replace oauth2Auth with alfrescoApi

* remove unneeded JS-API dep
move auth in the right place

* [AAE-10501] Rename alfresco-api.http-client to adf-http-client

* [AAE-10501] Remove config from a CoreModule, a different service is provided in AuthModule to use angular http client instead of super agent

* [AAE-10501] Disable AlfrescoApi oauth initialization while using new adf oidc authentication

* [AAE-12501] Replace alfresco api client with AdfHttpClient

* [AAE-12501] Restore get username methods

* [AAE-12501] Get username with authentication service

* [AAE-12501] removee unused method

* [AAE-12501] Trigger on login when token is received

* [AAE-12501] Fix content-services unit test

* [AAE-12501] Fix import

* [AAE-12501] Fix core unit tests

* [AAE-12501] Fix process-services-cloud unit tests

* [AAE-12501] Create a request options interface with the needed props, remove the import from js-api, return the body from request

* [AAE-12501] Fix process-services-cloud unit tests without Expectation

* [AAE-12501] Fix Core secondary entrypoints unit tests are not executed: move test.ts one level up in order to find all the spec files into the secondary entrypoints folders and update path

* [AAE-12501] Fix Core unit tests that weren't executed because of the previous test.ts wrong location

* [AAE-12501] Fix authentication token_issued subscription

* add emitters

* [AAE-12501] Replace Math.random() to fix hospot security issue, fix lint issues

* [AAE-12501] Install event-emitter dependency

* [AAE-12501] Comment temporary setCsrfToken because is not possible to import app config service from core due to circular dependencies

* [AAE-12501] Get disableCsrf from app config serviice when app configuration is loaded

* [AAE-12501] Fix license-header lint issue

* [AAE-14221] Regenerate lock file

* [AAE-14221] Fix sonarcloud issues

* [AAE-12501] Remove wrong character

* [AAE-12501] Regenerate lock file

* [AAE-12501] Fix BC: update alfresco api response error

---------

Co-authored-by: eromano <eugenioromano16@gmail.com>
This commit is contained in:
Amedeo Lepore
2023-06-27 17:22:30 +02:00
committed by GitHub
parent 037dce0ae7
commit 7abebf0652
53 changed files with 5474 additions and 10457 deletions

View File

@@ -20,7 +20,7 @@ import { from, Observable, throwError, Subject } from 'rxjs';
import { catchError, map, switchMap, filter, take } from 'rxjs/operators';
import { RepositoryInfo, SystemPropertiesRepresentation } from '@alfresco/js-api';
import { BpmProductVersionModel, AlfrescoApiService, AuthenticationService } from '@alfresco/adf-core';
import { BpmProductVersionModel, AuthenticationService } from '@alfresco/adf-core';
import { ApiClientsService } from '@alfresco/adf-core/api';
@Injectable({
@@ -34,13 +34,12 @@ export class DiscoveryApiService {
ecmProductInfo$ = new Subject<RepositoryInfo>();
constructor(
private apiService: AlfrescoApiService,
private authenticationService: AuthenticationService,
private apiClientsService: ApiClientsService
) {
this.authenticationService.onLogin
.pipe(
filter(() => this.apiService.getInstance()?.isEcmLoggedIn()),
filter(() => this.authenticationService.isEcmLoggedIn()),
take(1),
switchMap(() => this.getEcmProductInfo())
)

View File

@@ -45,7 +45,8 @@ export class SitesService {
return this._sitesApi;
}
constructor(private apiService: AlfrescoApiService, private logService: LogService) {
constructor(private apiService: AlfrescoApiService,
private logService: LogService) {
}
/**
@@ -140,15 +141,6 @@ export class SitesService {
return from(this.sitesApi.listSiteMemberships(siteId, opts));
}
/**
* Gets the username of the user currently logged into ACS.
*
* @returns Username string
*/
getEcmCurrentLoggedUserName(): string {
return this.apiService.getInstance().getEcmUsername();
}
/**
* Looks for a site inside the path of a Node and returns its guid if it finds one.
* (return an empty string if no site is found)

View File

@@ -17,7 +17,7 @@
import { Injectable } from '@angular/core';
import { Node } from '@alfresco/js-api';
import { AlfrescoApiService } from '@alfresco/adf-core';
import { AuthenticationService } from '@alfresco/adf-core';
import moment, { Moment } from 'moment';
@Injectable({
@@ -25,7 +25,7 @@ import moment, { Moment } from 'moment';
})
export class LockService {
constructor(private alfrescoApiService: AlfrescoApiService) {
constructor(private authService: AuthenticationService) {
}
isLocked(node: Node): boolean {
@@ -34,7 +34,7 @@ export class LockService {
if (this.isReadOnlyLock(node)) {
isLocked = !this.isLockExpired(node);
} else if (this.isLockOwnerAllowed(node)) {
isLocked = this.alfrescoApiService.getInstance().getEcmUsername() !== node.properties['cm:lockOwner'].id;
isLocked = this.authService.getEcmUsername() !== node.properties['cm:lockOwner'].id;
if (this.isLockExpired(node)) {
isLocked = false;
}

View File

@@ -19,7 +19,7 @@ import { DebugElement } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DropdownSitesComponent, Relations } from './sites-dropdown.component';
import { setupTestBed } from '@alfresco/adf-core';
import { AuthenticationService, setupTestBed } from '@alfresco/adf-core';
import { of } from 'rxjs';
import { getFakeSitePaging,
getFakeSitePagingNoMoreItems,
@@ -57,6 +57,7 @@ describe('DropdownSitesComponent', () => {
let debug: DebugElement;
let element: HTMLElement;
let siteService: SitesService;
let authService: AuthenticationService;
setupTestBed({
imports: [
@@ -293,10 +294,11 @@ describe('DropdownSitesComponent', () => {
beforeEach(() => {
component.relations = Relations.Members;
authService = TestBed.inject(AuthenticationService);
});
it('should show only sites which logged user is member of when member relation is set', (done) => {
spyOn(siteService, 'getEcmCurrentLoggedUserName').and.returnValue('test');
spyOn(authService, 'getEcmUsername').and.returnValue('test');
fixture.detectChanges();
fixture.whenStable().then(() => {
@@ -317,10 +319,11 @@ describe('DropdownSitesComponent', () => {
describe('No relations', () => {
beforeEach(() => {
component.relations = [];
authService = TestBed.inject(AuthenticationService);
});
it('should show all the sites if no relation is set', (done) => {
spyOn(siteService, 'getEcmCurrentLoggedUserName').and.returnValue('test');
spyOn(authService, 'getEcmUsername').and.returnValue('test');
fixture.detectChanges();
fixture.whenStable().then(() => {

View File

@@ -16,7 +16,7 @@
*/
import { Component, EventEmitter, Input, OnInit, Output, ViewEncapsulation } from '@angular/core';
import { LogService, InfiniteSelectScrollDirective } from '@alfresco/adf-core';
import { LogService, InfiniteSelectScrollDirective, AuthenticationService } from '@alfresco/adf-core';
import { SitePaging, SiteEntry } from '@alfresco/js-api';
import { MatSelectChange } from '@angular/material/select';
import {LiveAnnouncer} from '@angular/cdk/a11y';
@@ -81,7 +81,8 @@ export class DropdownSitesComponent implements OnInit {
selected: SiteEntry = null;
MY_FILES_VALUE = '-my-';
constructor(private sitesService: SitesService,
constructor(private authService: AuthenticationService,
private sitesService: SitesService,
private logService: LogService,
private liveAnnouncer: LiveAnnouncer,
private translateService: TranslateService) {
@@ -174,7 +175,7 @@ export class DropdownSitesComponent implements OnInit {
}
private filteredResultsByMember(sites: SitePaging): SitePaging {
const loggedUserName = this.sitesService.getEcmCurrentLoggedUserName();
const loggedUserName = this.authService.getEcmUsername();
sites.list.entries = sites.list.entries.filter((site) => this.isCurrentUserMember(site, loggedUserName));
return sites;
}

View File

@@ -19,4 +19,5 @@ export * from './lib/api-client.factory';
export * from './lib/api-clients.service';
export * from './lib/clients';
export * from './lib/types';
export * from './lib/alfresco-api/alfresco-api.http-client';
export * from './lib/adf-http-client.service';
export * from './lib/interfaces';

View File

@@ -19,8 +19,8 @@ import { Emitters, RequestOptions, ResultListDataRepresentationTaskRepresentatio
import { HttpParams } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { AlfrescoApiHttpClient } from './alfresco-api.http-client';
import { AlfrescoApiResponseError } from './alfresco-api.response-error';
import { AdfHttpClient } from './adf-http-client.service';
import { AlfrescoApiResponseError } from './alfresco-api/alfresco-api.response-error';
const securityOptions: SecurityOptions = {
authentications: {},
@@ -52,8 +52,8 @@ const mockResponse = {
]
};
describe('AlfrescoApiHttpClient', () => {
let angularHttpClient: AlfrescoApiHttpClient;
describe('AdfHttpClient', () => {
let angularHttpClient: AdfHttpClient;
let controller: HttpTestingController;
beforeEach(() => {
@@ -62,7 +62,7 @@ describe('AlfrescoApiHttpClient', () => {
HttpClientTestingModule
]
});
angularHttpClient = TestBed.inject(AlfrescoApiHttpClient);
angularHttpClient = TestBed.inject(AdfHttpClient);
controller = TestBed.inject(HttpTestingController);
});
@@ -90,7 +90,7 @@ describe('AlfrescoApiHttpClient', () => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
expect(res.data![0].created instanceof Date).toBeTruthy();
done();
});
}).catch(error=> fail(error));
const req = controller.expectOne('http://example.com');
expect(req.request.method).toEqual('POST');
@@ -110,7 +110,7 @@ describe('AlfrescoApiHttpClient', () => {
angularHttpClient.request('http://example.com', options, securityOptions, emitters).then((res) => {
expect(res).toEqual(mockResponse);
done();
});
}).catch(error=> fail(error));
const req = controller.expectOne('http://example.com');
expect(req.request.method).toEqual('POST');
@@ -177,7 +177,9 @@ describe('AlfrescoApiHttpClient', () => {
returnType: null
};
angularHttpClient.request('http://example.com', requestOptions, securityOptions, emitters);
angularHttpClient.request('http://example.com', requestOptions, securityOptions, emitters).catch(error =>
fail(error)
);
const req = controller.expectOne('http://example.com?autoRename=true&include=allowableOperations');
expect(req.request.method).toEqual('POST');
@@ -232,9 +234,9 @@ describe('AlfrescoApiHttpClient', () => {
const errorResponse = new Blob();
angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch((res: AlfrescoApiResponseError) => {
expect(res.status).toBe(400);
expect(res.error.response.body instanceof Blob).toBeTruthy();
angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch((err: AlfrescoApiResponseError) => {
expect(err.status).toBe(400);
expect(err.response.body instanceof Blob).toBeTruthy();
done();
});
@@ -257,7 +259,9 @@ describe('AlfrescoApiHttpClient', () => {
}
};
angularHttpClient.request('http://example.com/candidatebaseapp/query/v1/process-instances', options, securityOptions, emitters);
angularHttpClient.request('http://example.com/candidatebaseapp/query/v1/process-instances', options, securityOptions, emitters).catch(error =>
fail(error)
);
const req = controller.expectOne('http://example.com/candidatebaseapp/query/v1/process-instances?skipCount=0&status=RUNNING&status=SUSPENDED&sort=startDate%2CDESC');
expect(req.request.method).toEqual('POST');
@@ -274,7 +278,7 @@ describe('AlfrescoApiHttpClient', () => {
angularHttpClient.request('http://example.com', options, securityOptions, emitters).then((res) => {
expect(res).toEqual('');
done();
});
}).catch(error=> fail(error));
const req = controller.expectOne('http://example.com');
@@ -290,7 +294,9 @@ describe('AlfrescoApiHttpClient', () => {
}
};
angularHttpClient.request('http://example.com', options, securityOptions, emitters);
angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch(error =>
fail(error)
);
const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000%2B02%3A00');
@@ -306,7 +312,9 @@ describe('AlfrescoApiHttpClient', () => {
}
};
angularHttpClient.request('http://example.com', options, securityOptions, emitters);
angularHttpClient.request('http://example.com', options, securityOptions, emitters).catch(error =>
fail(error)
);
const req = controller.expectOne('http://example.com?lastModifiedFrom=2022-08-17T00%3A00%3A00.000Z');

View File

@@ -0,0 +1,353 @@
/*!
* @license
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { SHOULD_ADD_AUTH_TOKEN } from '@alfresco/adf-core/auth';
import { Emitters as JsApiEmitters, HttpClient as JsApiHttpClient } from '@alfresco/js-api';
import {
HttpClient,
HttpContext,
HttpErrorResponse,
HttpEvent,
HttpHeaders,
HttpParams,
HttpResponse
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of, Subject, throwError } from 'rxjs';
import { catchError, map, takeUntil } from 'rxjs/operators';
import {
convertObjectToFormData,
getQueryParamsWithCustomEncoder,
isBlobResponse,
isConstructor,
isHttpResponseEvent,
isHttpUploadProgressEvent,
removeNilValues
} from './alfresco-api/alfresco-api.utils';
import { AlfrescoApiParamEncoder } from './alfresco-api/alfresco-api.param-encoder';
import { AlfrescoApiResponseError } from './alfresco-api/alfresco-api.response-error';
import { Constructor } from './types';
import { RequestOptions, SecurityOptions } from './interfaces';
import ee, { Emitter } from 'event-emitter';
export interface Emitters {
readonly eventEmitter: Emitter;
readonly apiClientEmitter: Emitter;
}
@Injectable({
providedIn: 'root'
})
export class AdfHttpClient implements ee.Emitter,JsApiHttpClient {
on: ee.EmitterMethod;
off: ee.EmitterMethod;
once: ee.EmitterMethod;
emit: (type: string, ...args: any[]) => void;
private _disableCsrf = false;
private defaultSecurityOptions = {
withCredentials: true,
isBpmRequest: false,
authentications: {},
defaultHeaders: {}
};
get disableCsrf(): boolean {
return this._disableCsrf;
}
set disableCsrf(disableCsrf: boolean) {
this._disableCsrf = disableCsrf;
}
constructor(private httpClient: HttpClient
) {
ee(this);
}
setDefaultSecurityOption(options: any) {
this.defaultSecurityOptions = this.merge(this.defaultSecurityOptions, options);
}
merge(...objects): any {
const result = {};
objects.forEach((source) => {
Object.keys(source).forEach((prop) => {
if (prop in result && Array.isArray(result[prop])) {
result[prop] = result[prop].concat(source[prop]);
} else if (prop in result && typeof result[prop] === 'object') {
result[prop] = this.merge(result[prop], source[prop]);
} else {
result[prop] = source[prop];
}
});
});
return result;
}
request<T = any>(url: string, options?: RequestOptions, sc: SecurityOptions = this.defaultSecurityOptions, emitters?: JsApiEmitters): Promise<T> {
const body = AdfHttpClient.getBody(options);
const params = getQueryParamsWithCustomEncoder(options.queryParams, new AlfrescoApiParamEncoder());
const responseType = AdfHttpClient.getResponseType(options);
const context = new HttpContext().set(SHOULD_ADD_AUTH_TOKEN, true);
const security: SecurityOptions = {...this.defaultSecurityOptions, ...sc};
const headers = this.getHeaders(options);
if (!emitters) {
emitters = this.getEventEmitters();
}
const request = this.httpClient.request(
options.httpMethod,
url,
{
context,
...(body && {body}),
...(responseType && {responseType}),
...security,
...(params && {params}),
headers,
observe: 'events',
reportProgress: true
}
);
return this.requestWithLegacyEventEmitters<T>(request, emitters, options.returnType);
}
post<T = any>(url: string, options?: RequestOptions, sc?: SecurityOptions, emitters?: JsApiEmitters): Promise<T> {
return this.request<T>(url, {...options, httpMethod: 'POST'}, sc, emitters);
}
put<T = any>(url: string, options?: RequestOptions, sc?: SecurityOptions, emitters?: JsApiEmitters): Promise<T> {
return this.request<T>(url, {...options, httpMethod: 'PUT'}, sc, emitters);
}
get<T = any>(url: string, options?: RequestOptions, sc?: SecurityOptions, emitters?: JsApiEmitters): Promise<T> {
return this.request<T>(url, {...options, httpMethod: 'GET'}, sc, emitters);
}
delete<T = void>(url: string, options?: RequestOptions, sc?: SecurityOptions, emitters?: JsApiEmitters): Promise<T> {
return this.request<T>(url, {...options, httpMethod: 'DELETE'}, sc, emitters);
}
private addPromiseListeners<T = any>(promise: Promise<T>, eventEmitter: any) {
const eventPromise = Object.assign(promise, {
on() {
eventEmitter.on.apply(eventEmitter, arguments);
return this;
},
once() {
eventEmitter.once.apply(eventEmitter, arguments);
return this;
},
emit() {
eventEmitter.emit.apply(eventEmitter, arguments);
return this;
},
off() {
eventEmitter.off.apply(eventEmitter, arguments);
return this;
}
});
return eventPromise;
}
private getEventEmitters(): Emitters {
const apiClientEmitter = {
on: this.on.bind(this),
off: this.off.bind(this),
once: this.once.bind(this),
emit: this.emit.bind(this)
};
return {
apiClientEmitter,
eventEmitter: ee({})
};
}
private requestWithLegacyEventEmitters<T = any>(request$: Observable<HttpEvent<T>>, emitters: JsApiEmitters, returnType: any): Promise<T> {
const abort$ = new Subject<void>();
const {eventEmitter, apiClientEmitter} = emitters;
const promise = request$.pipe(
map((res) => {
if (isHttpUploadProgressEvent(res)) {
const percent = Math.round((res.loaded / res.total) * 100);
eventEmitter.emit('progress', {loaded: res.loaded, total: res.total, percent});
}
if (isHttpResponseEvent(res)) {
eventEmitter.emit('success', res.body);
return AdfHttpClient.deserialize(res, returnType);
}
}),
catchError((err: HttpErrorResponse): Observable<AlfrescoApiResponseError> => {
// since we can't always determinate ahead of time if the response is going to be xml or plain text response
// we need to handle false positive cases here.
if (err.status === 200) {
eventEmitter.emit('success', err.error.text);
return of(err.error.text);
}
eventEmitter.emit('error', err);
apiClientEmitter.emit('error', err);
if (err.status === 401) {
eventEmitter.emit('unauthorized');
apiClientEmitter.emit('unauthorized');
}
// for backwards compatibility we need to convert it to error class as the HttpErrorResponse only implements Error interface, not extending it,
// and we need to be able to correctly pass instanceof Error conditions used inside repository
// we also need to pass error as Stringify string as we are detecting statusCodes using JSON.parse(error.message) in some places
const msg = typeof err.error === 'string' ? err.error : JSON.stringify(err.error);
// for backwards compatibility to handle cases in code where we try read response.error.response.body;
const error = {
response: {...err, body: err.error}
};
const alfrescoApiError = new AlfrescoApiResponseError(msg, err.status, error.response);
return throwError(alfrescoApiError);
}),
takeUntil(abort$)
).toPromise();
(promise as any).abort = function() {
eventEmitter.emit('abort');
abort$.next();
abort$.complete();
return this;
};
return this.addPromiseListeners(promise, eventEmitter);
}
private static getBody(options: RequestOptions): any {
const contentType = options.contentType;
const isFormData = contentType === 'multipart/form-data';
const isFormUrlEncoded = contentType === 'application/x-www-form-urlencoded';
const body = options.bodyParam;
if (isFormData) {
return convertObjectToFormData(options.formParams);
}
if (isFormUrlEncoded) {
return new HttpParams({fromObject: removeNilValues(options.formParams)});
}
return body;
}
private getHeaders(options: RequestOptions): HttpHeaders {
const optionsHeaders = {
...options.headerParams,
...(options.accept && {Accept: options.accept}),
...((options.contentType) && {'Content-Type': options.contentType})
};
if (!this.disableCsrf) {
this.setCsrfToken(optionsHeaders);
}
return new HttpHeaders(optionsHeaders);
}
private setCsrfToken(optionsHeaders: any) {
const token = this.createCSRFToken();
optionsHeaders['X-CSRF-TOKEN'] = token;
try {
document.cookie = 'CSRF-TOKEN=' + token + ';path=/';
} catch (err) {
/* continue regardless of error */
}
}
private createCSRFToken(a?: any): string {
const randomValue = window.crypto.getRandomValues(new Uint32Array(1))[0];
return a ? (a ^ ((randomValue * 16) >> (a / 4))).toString(16) : ([1e16] + (1e16).toString()).replace(/[01]/g, this.createCSRFToken);
}
private static getResponseType(options: RequestOptions): 'blob' | 'json' | 'text' {
const isBlobType = options.returnType?.toString().toLowerCase() === 'blob' || options.responseType?.toString().toLowerCase() === 'blob';
if (isBlobType) {
return 'blob';
}
if (options.returnType === 'String') {
return 'text';
}
return 'json';
}
/**
* Deserialize an HTTP response body into a value of the specified type.
*/
private static deserialize<T>(response: HttpResponse<T>, returnType?: Constructor<unknown> | 'blob'): any {
if (response === null) {
return null;
}
const body = response.body;
if (!returnType) {
// for backwards compatibility we need to return empty string instead of null,
// to avoid issues when accessing null response would break application [C309878]
// cannot read property 'entry' of null in cases like
// return this.post(apiUrl, saveFormRepresentation).pipe(map((res: any) => res.entry))
return body !== null ? body : '';
}
if (isBlobResponse(response, returnType)) {
return AdfHttpClient.deserializeBlobResponse(response);
}
if (!isConstructor(returnType)) {
return body;
}
if (Array.isArray(body)) {
return body.map((element) => new returnType(element));
}
return new returnType(body);
}
private static deserializeBlobResponse(response: HttpResponse<Blob>) {
return new Blob([response.body], {type: response.headers.get('Content-Type')});
}
}

View File

@@ -1,227 +0,0 @@
/*!
* @license
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { SHOULD_ADD_AUTH_TOKEN } from '@alfresco/adf-core/auth';
import { Emitters as JsApiEmitters, HttpClient as JsApiHttpClient, RequestOptions, SecurityOptions, isBrowser } from '@alfresco/js-api';
import { HttpClient, HttpContext, HttpErrorResponse, HttpEvent, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of, Subject, throwError } from 'rxjs';
import { catchError, map, takeUntil } from 'rxjs/operators';
import { convertObjectToFormData, getQueryParamsWithCustomEncoder, isBlobResponse, isConstructor, isHttpResponseEvent, isHttpUploadProgressEvent, removeNilValues } from './alfresco-api.utils';
import { AlfrescoApiParamEncoder } from './alfresco-api.param-encoder';
import { AlfrescoApiResponseError } from './alfresco-api.response-error';
import { Constructor } from '../types';
@Injectable({
providedIn: 'root'
})
export class AlfrescoApiHttpClient implements JsApiHttpClient {
constructor(private httpClient: HttpClient) {}
request<T = any>(url: string, options: RequestOptions, sc: SecurityOptions, emitters: JsApiEmitters): Promise<T> {
const body = AlfrescoApiHttpClient.getBody(options);
const params = getQueryParamsWithCustomEncoder(options.queryParams, new AlfrescoApiParamEncoder());
const headers = AlfrescoApiHttpClient.getHeaders(options);
const responseType = AlfrescoApiHttpClient.getResponseType(options);
const context = new HttpContext().set(SHOULD_ADD_AUTH_TOKEN, true);
const request = this.httpClient.request(
options.httpMethod,
url,
{
context,
...(body && { body }),
...(responseType && { responseType }),
...(sc.withCredentials && { withCredentials: true }),
...(params && { params }),
headers,
observe: 'events',
reportProgress: true
}
);
return this.requestWithLegacyEventEmitters<T>(request, emitters, options.returnType);
}
post<T = any>(url: string, options: RequestOptions, sc: SecurityOptions, emitters: JsApiEmitters): Promise<T> {
return this.request<T>(url, { ...options, httpMethod: 'POST' }, sc, emitters);
}
put<T = any>(url: string, options: RequestOptions, sc: SecurityOptions, emitters: JsApiEmitters): Promise<T> {
return this.request<T>(url, { ...options, httpMethod: 'PUT' }, sc, emitters);
}
get<T = any>(url: string, options: RequestOptions, sc: SecurityOptions, emitters: JsApiEmitters): Promise<T> {
return this.request<T>(url, { ...options, httpMethod: 'GET' }, sc, emitters);
}
delete<T = void>(url: string, options: RequestOptions, sc: SecurityOptions, emitters: JsApiEmitters): Promise<T> {
return this.request<T>(url, { ...options, httpMethod: 'DELETE' }, sc, emitters);
}
private requestWithLegacyEventEmitters<T = any>(request$: Observable<HttpEvent<T>>, emitters: JsApiEmitters, returnType: any): Promise<T> {
const abort$ = new Subject<void>();
const { eventEmitter, apiClientEmitter } = emitters;
const promise = request$.pipe(
map((res) => {
if (isHttpUploadProgressEvent(res)) {
const percent = Math.round((res.loaded / res.total) * 100);
eventEmitter.emit('progress', { loaded: res.loaded, total: res.total, percent });
}
if (isHttpResponseEvent(res)) {
eventEmitter.emit('success', res.body);
return AlfrescoApiHttpClient.deserialize(res, returnType);
}
}),
catchError((err: HttpErrorResponse): Observable<AlfrescoApiResponseError> => {
// since we can't always determinate ahead of time if the response is going to be xml or plain text response
// we need to handle false positive cases here.
if (err.status === 200) {
eventEmitter.emit('success', err.error.text);
return of(err.error.text);
}
eventEmitter.emit('error', err);
apiClientEmitter.emit('error', err);
if (err.status === 401) {
eventEmitter.emit('unauthorized');
apiClientEmitter.emit('unauthorized');
}
// for backwards compatibility we need to convert it to error class as the HttpErrorResponse only implements Error interface, not extending it,
// and we need to be able to correctly pass instanceof Error conditions used inside repository
// we also need to pass error as Stringify string as we are detecting statusCodes using JSON.parse(error.message) in some places
const msg = typeof err.error === 'string' ? err.error : JSON.stringify(err.error);
// for backwards compatibility to handle cases in code where we try read response.error.response.body;
const error = {
response: { ...err, body: err.error }
};
const alfrescoApiError = new AlfrescoApiResponseError(msg, err.status, error);
return throwError(alfrescoApiError);
}),
takeUntil(abort$)
).toPromise();
(promise as any).abort = function() {
eventEmitter.emit('abort');
abort$.next();
abort$.complete();
return this;
};
return promise;
}
private static getBody(options: RequestOptions): any {
const contentType = options.contentType;
const isFormData = contentType === 'multipart/form-data';
const isFormUrlEncoded = contentType === 'application/x-www-form-urlencoded';
const body = options.bodyParam;
if (isFormData) {
return convertObjectToFormData(options.formParams);
}
if (isFormUrlEncoded) {
return new HttpParams({ fromObject: removeNilValues(options.formParams) });
}
return body;
}
private static getHeaders(options: RequestOptions): HttpHeaders {
const optionsHeaders = {
...options.headerParams,
...(options.accept && { Accept: options.accept }),
...((options.contentType) && { 'Content-Type': options.contentType })
};
return new HttpHeaders(optionsHeaders);
}
private static getResponseType(options: RequestOptions): 'blob' | 'json' | 'text' {
const isBlobType = options.returnType?.toString().toLowerCase() === 'blob' || options.responseType?.toString().toLowerCase() === 'blob';
if (isBlobType) {
return 'blob';
}
if (options.returnType === 'String') {
return 'text';
}
return 'json';
}
/**
* Deserialize an HTTP response body into a value of the specified type.
*/
private static deserialize<T>(response: HttpResponse<T>, returnType?: Constructor<unknown> | 'blob'): any {
if (response === null) {
return null;
}
const body = response.body;
if (!returnType) {
// for backwards compatibility we need to return empty string instead of null,
// to avoid issues when accessing null response would break application [C309878]
// cannot read property 'entry' of null in cases like
// return this.post(apiUrl, saveFormRepresentation).pipe(map((res: any) => res.entry))
return body !== null ? body : '';
}
if (isBlobResponse(response, returnType)) {
return AlfrescoApiHttpClient.deserializeBlobResponse(response);
}
if (!isConstructor(returnType)) {
return body;
}
if (Array.isArray(body)) {
return body.map((element) => new returnType(element));
}
return new returnType(body);
}
private static deserializeBlobResponse(response: HttpResponse<Blob>) {
if (isBrowser()) {
return new Blob([response.body], { type: response.headers.get('Content-Type') });
}
return Buffer.from(response.body as unknown as WithImplicitCoercion<string>, 'binary');
}
}

View File

@@ -19,7 +19,7 @@ export class AlfrescoApiResponseError extends Error {
public name = 'AlfrescoApiResponseError';
constructor(msg: string, public status: number, public error: { response: Record<string, any> }) {
constructor(msg: string, public status: number, public response: Record<string, any> ) {
super(msg);
}
}

View File

@@ -0,0 +1,36 @@
/*!
* @license
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export interface RequestOptions {
httpMethod?: string;
queryParams?: any;
headerParams?: any;
formParams?: any;
bodyParam?: any;
returnType?: any;
responseType?: string;
readonly accept?: string;
readonly contentType?: string;
}
export interface SecurityOptions {
readonly isBpmRequest: boolean;
readonly enableCsrf?: boolean;
readonly withCredentials?: boolean;
readonly authentications: any;
readonly defaultHeaders: Record<string, string>;
}

View File

@@ -48,6 +48,7 @@ describe('AuthenticationInterceptor', () => {
});
it('should call add auth token method when SHOULD_ADD_AUTH_TOKEN context is set to true', () => {
addTokenToHeaderSpy.and.callThrough();
request.context.set(SHOULD_ADD_AUTH_TOKEN, true);
interceptor.intercept(request, mockNext);
expect(addTokenToHeaderSpy).toHaveBeenCalled();

View File

@@ -26,6 +26,7 @@ import { CommonModule } from '@angular/common';
import { ShellAppService, SHELL_APP_SERVICE } from '../../services/shell-app.service';
import { HttpClientModule } from '@angular/common/http';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { TranslateModule } from '@ngx-translate/core';
class MockRouter {
private url = 'some-url';
@@ -57,7 +58,15 @@ describe('AppLayoutComponent', () => {
};
TestBed.configureTestingModule({
imports: [CommonModule, NoopAnimationsModule, HttpClientModule, SidenavLayoutModule, ExtensionsModule, RouterModule.forChild([])],
imports: [
CommonModule,
NoopAnimationsModule,
HttpClientModule,
SidenavLayoutModule,
ExtensionsModule,
RouterModule.forChild([]),
TranslateModule.forRoot()
],
providers: [
{
provide: Router,

View File

@@ -15,7 +15,7 @@
* limitations under the License.
*/
import { AlfrescoApiHttpClient } from '@alfresco/adf-core/api';
import { AdfHttpClient } from '@alfresco/adf-core/api';
import { StorageService } from '../common/services/storage.service';
import { AlfrescoApi, AlfrescoApiConfig } from '@alfresco/js-api';
import { Injectable } from '@angular/core';
@@ -23,16 +23,19 @@ import { AppConfigService } from '../app-config';
import { AlfrescoApiService } from '../services/alfresco-api.service';
@Injectable()
export class AlfrescoApiServiceWithAngularBasedHttpClient extends AlfrescoApiService {
export class AlfrescoApiNoAuthService extends AlfrescoApiService {
constructor(
storage: StorageService,
appConfig: AppConfigService,
private readonly alfrescoApiHttpClient: AlfrescoApiHttpClient
private readonly adfHttpClient: AdfHttpClient
) {
super(appConfig, storage);
}
override createInstance(config: AlfrescoApiConfig) {
return new AlfrescoApi(config, this.alfrescoApiHttpClient);
return new AlfrescoApi({
...config,
oauthInit: false
}, this.adfHttpClient);
}
}

View File

@@ -17,9 +17,11 @@
import { AppConfigService, AppConfigValues } from './app-config.service';
import { StorageService } from '../common/services/storage.service';
import { AdfHttpClient } from '@alfresco/adf-core/api';
export function loadAppConfig(appConfigService: AppConfigService, storageService: StorageService) {
export function loadAppConfig(appConfigService: AppConfigService, storageService: StorageService, adfHttpClient: AdfHttpClient) {
return () => appConfigService.load().then(() => {
adfHttpClient.disableCsrf = appConfigService.get<boolean>(AppConfigValues.DISABLECSRF);
storageService.prefix = appConfigService.get<string>(AppConfigValues.STORAGE_PREFIX, '');
});
}

View File

@@ -17,7 +17,7 @@
import { APP_INITIALIZER, ModuleWithProviders, NgModule } from '@angular/core';
import { AuthConfig, AUTH_CONFIG, OAuthModule, OAuthService, OAuthStorage } from 'angular-oauth2-oidc';
import { AlfrescoApiServiceWithAngularBasedHttpClient } from '../../api-factories/alfresco-api-service-with-angular-based-http-client';
import { AlfrescoApiNoAuthService } from '../../api-factories/alfresco-api-no-auth.service';
import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { AuthGuardBpm } from '../guard/auth-guard-bpm.service';
import { AuthGuardEcm } from '../guard/auth-guard-ecm.service';
@@ -47,7 +47,7 @@ export function loginFactory(oAuthService: OAuthService, storage: OAuthStorage,
{ provide: AuthGuardEcm, useClass: OidcAuthGuard },
{ provide: AuthGuardBpm, useClass: OidcAuthGuard },
{ provide: AuthenticationService, useClass: OIDCAuthenticationService },
{ provide: AlfrescoApiService, useClass: AlfrescoApiServiceWithAngularBasedHttpClient },
{ provide: AlfrescoApiService, useClass: AlfrescoApiNoAuthService },
{
provide: AUTH_CONFIG,
useFactory: authConfigFactory,

View File

@@ -16,11 +16,11 @@
*/
import { Injectable, inject } from '@angular/core';
import { OAuthService, OAuthStorage } from 'angular-oauth2-oidc';
import { OAuthEvent, OAuthService, OAuthStorage } from 'angular-oauth2-oidc';
import { EMPTY, Observable } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { catchError, filter, map } from 'rxjs/operators';
import { AppConfigValues } from '../../app-config/app-config.service';
import { BaseAuthenticationService } from '../../services/base-authentication.service';
import { BaseAuthenticationService } from '../services/base-authentication.service';
import { JwtHelperService } from '../services/jwt-helper.service';
import { AuthConfigService } from '../oidc/auth-config.service';
import { AuthService } from './auth.service';
@@ -39,7 +39,9 @@ export class OIDCAuthenticationService extends BaseAuthenticationService {
constructor() {
super();
this.alfrescoApi.alfrescoApiInitialized.subscribe(() => {
this.alfrescoApi.getInstance().reply('logged-in', () => {
this.oauthService.events.pipe(
filter((event)=> event.type === 'token_received')
).subscribe(()=>{
this.onLogin.next();
});
});
@@ -87,6 +89,14 @@ export class OIDCAuthenticationService extends BaseAuthenticationService {
);
}
getEcmUsername(): string {
return (this.oauthService.getIdentityClaims() as any).preferred_username;
}
getBpmUsername(): string {
return (this.oauthService.getIdentityClaims() as any).preferred_username;
}
ssoImplicitLogin() {
this.oauthService.initLoginFlow();
}
@@ -117,4 +127,8 @@ export class OIDCAuthenticationService extends BaseAuthenticationService {
this.auth.login();
}
}
once(event: string): Observable<OAuthEvent> {
return this.oauthService.events.pipe(filter(_event => _event.type === event));
}
}

View File

@@ -21,7 +21,7 @@ import { AppConfigValues } from '../../app-config/app-config.service';
import { map, catchError, tap } from 'rxjs/operators';
import { JwtHelperService } from './jwt-helper.service';
import { StorageService } from '../../common/services/storage.service';
import { BaseAuthenticationService } from '../../services/base-authentication.service';
import { BaseAuthenticationService } from './base-authentication.service';
@Injectable({
providedIn: 'root'
@@ -152,6 +152,24 @@ export class AuthenticationService extends BaseAuthenticationService {
return false;
}
/**
* Gets the ECM username.
*
* @returns The ECM username
*/
getEcmUsername(): string {
return this.alfrescoApi.getInstance().getEcmUsername();
}
/**
* Gets the BPM username
*
* @returns The BPM username
*/
getBpmUsername(): string {
return this.alfrescoApi.getInstance().getBpmUsername();
}
isImplicitFlow(): boolean {
return !!this.appConfig.oauth2?.implicitFlow;
}
@@ -169,5 +187,12 @@ export class AuthenticationService extends BaseAuthenticationService {
return this.storageService.getItem(JwtHelperService.USER_ACCESS_TOKEN);
}
reset() {}
reset() { }
once(event: string): Observable<any> {
const alfrescoApiEvent = event === 'token_received' ? 'token_issued' : event;
return new Observable((subscriber) => {
this.alfrescoApi.getInstance().oauth2Auth.once(alfrescoApiEvent, () => subscriber.next());
});
}
}

View File

@@ -15,14 +15,14 @@
* limitations under the License.
*/
import { PeopleApi, UserProfileApi, UserRepresentation } from '@alfresco/js-api';
import { PeopleApi, UserProfileApi } from '@alfresco/js-api';
import { HttpHeaders } from '@angular/common/http';
import { RedirectionModel } from '../auth/models/redirection.model';
import { from, Observable, Observer, ReplaySubject, throwError } from 'rxjs';
import { AppConfigService, AppConfigValues } from '../app-config/app-config.service';
import { AlfrescoApiService } from './alfresco-api.service';
import { CookieService } from '../common/services/cookie.service';
import { LogService } from '../common/services/log.service';
import { RedirectionModel } from '../models/redirection.model';
import { Observable, Observer, ReplaySubject, throwError } from 'rxjs';
import { AppConfigService, AppConfigValues } from '../../app-config/app-config.service';
import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { CookieService } from '../../common/services/cookie.service';
import { LogService } from '../../common/services/log.service';
import { inject } from '@angular/core';
const REMEMBER_ME_COOKIE_KEY = 'ALFRESCO_REMEMBER_ME';
@@ -57,14 +57,15 @@ export abstract class BaseAuthenticationService {
abstract isLoggedIn(): boolean;
abstract isLoggedInWith(provider: string): boolean;
abstract isOauth(): boolean;
abstract isImplicitFlow(): boolean;
abstract isAuthCodeFlow(): boolean;
abstract login(username: string, password: string, rememberMe?: boolean): Observable<{ type: string; ticket: any }>;
abstract ssoImplicitLogin(): void;
abstract logout(): Observable<any>;
abstract isEcmLoggedIn(): boolean;
abstract isBpmLoggedIn(): boolean;
abstract getEcmUsername(): string;
abstract getBpmUsername(): string;
abstract reset(): void;
abstract once(event: string): Observable<any>;
getBearerExcludedUrls(): readonly string[] {
return this.bearerExcludedUrls;
@@ -126,24 +127,6 @@ export abstract class BaseAuthenticationService {
return header.set('Authorization', ticket);
}
/**
* Gets the ECM username.
*
* @returns The ECM username
*/
getEcmUsername(): string {
return this.alfrescoApi.getInstance().getEcmUsername();
}
/**
* Gets the BPM username
*
* @returns The BPM username
*/
getBpmUsername(): string {
return this.alfrescoApi.getInstance().getBpmUsername();
}
isPublicUrl(): boolean {
return this.alfrescoApi.getInstance().isPublicUrl();
}
@@ -206,15 +189,6 @@ export abstract class BaseAuthenticationService {
return null;
}
/**
* Gets information about the user currently logged into APS.
*
* @returns User information
*/
getBpmLoggedUser(): Observable<UserRepresentation> {
return from(this.profileApi.getProfile());
}
/**
* Prints an error message in the console browser
*

View File

@@ -17,7 +17,6 @@
import { fakeAsync, TestBed } from '@angular/core/testing';
import { setupTestBed } from '../../testing/setup-test-bed';
import { AlfrescoApiService } from './../../services/alfresco-api.service';
import { IdentityGroupService } from './identity-group.service';
import { HttpErrorResponse } from '@angular/common/http';
import { throwError, of } from 'rxjs';
@@ -25,23 +24,18 @@ import {
mockIdentityRoles,
clientRoles,
mockIdentityGroup1,
mockIdentityGroupsCount
mockIdentityGroupsCount,
mockIdentityGroups,
roleMappingMock
} from '../mock/identity-group.mock';
import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import {
applicationDetailsMockApi,
createGroupMappingApi,
deleteGroupMappingApi,
groupsMockApi,
noRoleMappingApi,
roleMappingApi,
updateGroupMappingApi
} from '../mock/oauth2.service.mock';
import { AdfHttpClient } from '../../../../api/src';
describe('IdentityGroupService', () => {
let service: IdentityGroupService;
let apiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
setupTestBed({
imports: [
@@ -52,11 +46,12 @@ describe('IdentityGroupService', () => {
beforeEach(fakeAsync(() => {
service = TestBed.inject(IdentityGroupService);
apiService = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request');
}));
it('should be able to fetch groups based on group name', (done) => {
spyOn(apiService, 'getInstance').and.returnValue(groupsMockApi);
requestSpy.and.returnValue(Promise.resolve(mockIdentityGroups));
service.findGroupsByName({name: 'mock'}).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -72,7 +67,7 @@ describe('IdentityGroupService', () => {
});
it('should return true if group has client role mapping', (done) => {
spyOn(apiService, 'getInstance').and.returnValue(roleMappingApi);
requestSpy.and.returnValue(Promise.resolve(roleMappingMock));
service.checkGroupHasClientApp('mock-group-id', 'mock-app-id').subscribe((hasRole) => {
expect(hasRole).toBeDefined();
expect(hasRole).toBe(true);
@@ -81,7 +76,7 @@ describe('IdentityGroupService', () => {
});
it('should return false if group does not have client role mapping', (done) => {
spyOn(apiService, 'getInstance').and.returnValue(noRoleMappingApi);
requestSpy.and.returnValue(Promise.resolve([]));
service.checkGroupHasClientApp('mock-group-id', 'mock-app-id').subscribe((hasRole) => {
expect(hasRole).toBeDefined();
expect(hasRole).toBe(false);
@@ -226,7 +221,7 @@ describe('IdentityGroupService', () => {
});
it('should be able to fetch the client id', (done) => {
spyOn(apiService, 'getInstance').and.returnValue(applicationDetailsMockApi);
requestSpy.and.returnValue(Promise.resolve([{id: 'mock-app-id', name: 'mock-app-name'}]));
service.getClientIdByApplicationName('mock-app-name').subscribe((clientId) => {
expect(clientId).toBeDefined();
expect(clientId).not.toBeNull();
@@ -236,7 +231,7 @@ describe('IdentityGroupService', () => {
});
it('should be able to all fetch groups', (done) => {
spyOn(apiService, 'getInstance').and.returnValue(groupsMockApi);
requestSpy.and.returnValue(Promise.resolve(mockIdentityGroups));
service.getGroups().subscribe((res) => {
expect(res.length).toBe(5);
expect(res[0].id).toBe('mock-group-id-1');
@@ -273,7 +268,7 @@ describe('IdentityGroupService', () => {
it('should be able to query groups based on first & max params', (done) => {
spyOn(service, 'getTotalGroupsCount').and.returnValue(of(mockIdentityGroupsCount));
spyOn(apiService, 'getInstance').and.returnValue(groupsMockApi);
requestSpy.and.returnValue(Promise.resolve(mockIdentityGroups));
service.queryGroups({first: 0, max: 5}).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -314,7 +309,7 @@ describe('IdentityGroupService', () => {
});
it('should be able to create group', (done) => {
const createCustomApiSpy = spyOn(apiService, 'getInstance').and.returnValue(createGroupMappingApi);
const createCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.createGroup(mockIdentityGroup1).subscribe(() => {
expect(createCustomApiSpy).toHaveBeenCalled();
done();
@@ -344,7 +339,7 @@ describe('IdentityGroupService', () => {
});
it('should be able to update group', (done) => {
const updateCustomApiSpy = spyOn(apiService, 'getInstance').and.returnValue(updateGroupMappingApi);
const updateCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.updateGroup('mock-group-id', mockIdentityGroup1).subscribe(() => {
expect(updateCustomApiSpy).toHaveBeenCalled();
done();
@@ -374,7 +369,7 @@ describe('IdentityGroupService', () => {
});
it('should be able to delete group', (done) => {
const deleteCustomApiSpy = spyOn(apiService, 'getInstance').and.returnValue(deleteGroupMappingApi);
const deleteCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.deleteGroup('mock-group-id').subscribe(() => {
expect(deleteCustomApiSpy).toHaveBeenCalled();
done();

View File

@@ -22,31 +22,20 @@ import {
mockIdentityUser1,
mockIdentityUser2,
mockIdentityRole,
mockIdentityUsers
mockIdentityUsers,
mockAssignedRoles,
mockAvailableRoles,
mockEffectiveRoles
} from '../mock/identity-user.mock';
import { mockJoinGroupRequest } from '../mock/identity-group.mock';
import { mockGroups, mockJoinGroupRequest } from '../mock/identity-group.mock';
import { IdentityUserService } from './identity-user.service';
import { JwtHelperService } from './jwt-helper.service';
import { setupTestBed } from '../../testing/setup-test-bed';
import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { mockToken } from '../mock/jwt-helper.service.spec';
import { IdentityRoleModel } from '../models/identity-role.model';
import { CoreTestingModule } from '../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import {
assignRolesMockApi,
createUserMockApi,
deleteUserMockApi,
getAssignedRolesMockApi,
getAvailableRolesMockApi,
getEffectiveRolesMockApi,
getInvolvedGroupsMockApi,
joinGroupMockApi,
leaveGroupMockApi,
queryUsersMockApi,
removeRolesMockApi,
updateUserMockApi
} from '../mock/oauth2.service.mock';
import { AdfHttpClient } from '../../../../api/src';
describe('IdentityUserService', () => {
@@ -59,7 +48,8 @@ describe('IdentityUserService', () => {
];
let service: IdentityUserService;
let alfrescoApiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
setupTestBed({
imports: [
@@ -70,7 +60,8 @@ describe('IdentityUserService', () => {
beforeEach(() => {
service = TestBed.inject(IdentityUserService);
alfrescoApiService = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request');
});
beforeEach(() => {
@@ -297,7 +288,7 @@ describe('IdentityUserService', () => {
});
it('should be able to query users based on query params (first & max params)', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(queryUsersMockApi);
requestSpy.and.returnValue(Promise.resolve(mockIdentityUsers));
service.queryUsers({first: 0, max: 5}).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -335,7 +326,7 @@ describe('IdentityUserService', () => {
});
it('should be able to create user', (done) => {
const createCustomApiSpy = spyOn(alfrescoApiService, 'getInstance').and.returnValue(createUserMockApi);
const createCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.createUser(mockIdentityUser1).subscribe(() => {
expect(createCustomApiSpy).toHaveBeenCalled();
done();
@@ -365,7 +356,7 @@ describe('IdentityUserService', () => {
});
it('should be able to update user', (done) => {
const updateCustomApiSpy = spyOn(alfrescoApiService, 'getInstance').and.returnValue(updateUserMockApi);
const updateCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.updateUser('mock-id-2', mockIdentityUser2).subscribe(() => {
expect(updateCustomApiSpy).toHaveBeenCalled();
done();
@@ -395,7 +386,7 @@ describe('IdentityUserService', () => {
});
it('should be able to delete group', (done) => {
const deleteCustomApiSpy = spyOn(alfrescoApiService, 'getInstance').and.returnValue(deleteUserMockApi);
const deleteCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.deleteUser('mock-user-id').subscribe(() => {
expect(deleteCustomApiSpy).toHaveBeenCalled();
done();
@@ -425,7 +416,7 @@ describe('IdentityUserService', () => {
});
it('should be able to fetch involved groups based on user id', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(getInvolvedGroupsMockApi);
requestSpy.and.returnValue(Promise.resolve(mockGroups));
service.getInvolvedGroups('mock-user-id').subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -461,7 +452,7 @@ describe('IdentityUserService', () => {
});
it('should be able to join the group', (done) => {
const joinGroupCustomApiSpy = spyOn(alfrescoApiService, 'getInstance').and.returnValue(joinGroupMockApi);
const joinGroupCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.joinGroup(mockJoinGroupRequest).subscribe(() => {
expect(joinGroupCustomApiSpy).toHaveBeenCalled();
done();
@@ -491,7 +482,7 @@ describe('IdentityUserService', () => {
});
it('should be able to leave the group', (done) => {
const leaveGroupCustomApiSpy = spyOn(alfrescoApiService, 'getInstance').and.returnValue(leaveGroupMockApi);
const leaveGroupCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.leaveGroup('mock-user-id', 'mock-group-id').subscribe(() => {
expect(leaveGroupCustomApiSpy).toHaveBeenCalled();
done();
@@ -521,7 +512,7 @@ describe('IdentityUserService', () => {
});
it('should be able to fetch available roles based on user id', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(getAvailableRolesMockApi);
requestSpy.and.returnValue(Promise.resolve(mockAvailableRoles));
service.getAvailableRoles('mock-user-id').subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -559,7 +550,7 @@ describe('IdentityUserService', () => {
});
it('should be able to fetch assigned roles based on user id', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(getAssignedRolesMockApi);
requestSpy.and.returnValue(Promise.resolve(mockAssignedRoles));
service.getAssignedRoles('mock-user-id').subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -597,7 +588,7 @@ describe('IdentityUserService', () => {
});
it('should be able to fetch effective roles based on user id', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(getEffectiveRolesMockApi);
requestSpy.and.returnValue(Promise.resolve(mockEffectiveRoles));
service.getEffectiveRoles('mock-user-id').subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -635,7 +626,7 @@ describe('IdentityUserService', () => {
});
it('should be able to assign roles to the user', (done) => {
const assignRolesCustomApiSpy = spyOn(alfrescoApiService, 'getInstance').and.returnValue(assignRolesMockApi);
const assignRolesCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.assignRoles('mock-user-id', [mockIdentityRole]).subscribe(() => {
expect(assignRolesCustomApiSpy).toHaveBeenCalled();
done();
@@ -665,7 +656,7 @@ describe('IdentityUserService', () => {
});
it('should be able to remove roles', (done) => {
const removeRolesCustomApiSpy = spyOn(alfrescoApiService, 'getInstance').and.returnValue(removeRolesMockApi);
const removeRolesCustomApiSpy = requestSpy.and.returnValue(Promise.resolve());
service.removeRoles('mock-user-id', [mockIdentityRole]).subscribe(() => {
expect(removeRolesCustomApiSpy).toHaveBeenCalled();
done();

View File

@@ -16,9 +16,8 @@
*/
import { Injectable } from '@angular/core';
import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { Observable, from } from 'rxjs';
import { Oauth2Auth } from '@alfresco/js-api';
import { AdfHttpClient } from '@alfresco/adf-core/api';
export const JSON_TYPE = ['application/json'];
@@ -32,25 +31,21 @@ export interface OAuth2RequestParams {
@Injectable({ providedIn: 'root' })
export class OAuth2Service {
constructor(private alfrescoApiService: AlfrescoApiService) {}
get apiClient(): Oauth2Auth {
return this.alfrescoApiService.getInstance().oauth2Auth;
}
constructor(private adfHttpClient: AdfHttpClient) {}
request<T>(opts: OAuth2RequestParams): Observable<T> {
const { httpMethod, url, bodyParam, queryParams } = opts;
return from(
this.apiClient.callCustomApi(
opts.url,
opts.httpMethod,
opts.pathParams,
opts.queryParams,
{},
{},
opts.bodyParam,
JSON_TYPE,
JSON_TYPE,
Object
this.adfHttpClient.request(
url,
{
httpMethod,
queryParams,
headerParams: {},
formParams: {},
bodyParam,
returnType: Object
}
)
);
}

View File

@@ -45,7 +45,6 @@ import { BlankPageModule } from './blank-page/blank-page.module';
import { DirectiveModule } from './directives/directive.module';
import { PipeModule } from './pipes/pipe.module';
import { AlfrescoApiService } from './services/alfresco-api.service';
import { TranslationService } from './translation/translation.service';
import { SortingPickerModule } from './sorting-picker/sorting-picker.module';
import { IconModule } from './icon/icon.module';
@@ -54,7 +53,7 @@ import { ExtensionsModule } from '@alfresco/adf-extensions';
import { directionalityConfigFactory } from './common/services/directionality-config-factory';
import { DirectionalityConfigService } from './common/services/directionality-config.service';
import { SearchTextModule } from './search-text/search-text-input.module';
import { AlfrescoJsClientsModule } from '@alfresco/adf-core/api';
import { AdfHttpClient, AlfrescoJsClientsModule } from '@alfresco/adf-core/api';
import { AuthenticationInterceptor, Authentication } from '@alfresco/adf-core/auth';
import { LegacyApiClientModule } from './api-factories/legacy-api-client.module';
import { HttpClientModule, HttpClientXsrfModule, HTTP_INTERCEPTORS } from '@angular/common/http';
@@ -65,13 +64,6 @@ import { loadAppConfig } from './app-config/app-config.loader';
import { AppConfigService } from './app-config/app-config.service';
import { StorageService } from './common/services/storage.service';
import { AlfrescoApiLoaderService, createAlfrescoApiInstance } from './api-factories/alfresco-api-v2-loader.service';
import { AlfrescoApiServiceWithAngularBasedHttpClient } from './api-factories/alfresco-api-service-with-angular-based-http-client';
interface Config {
readonly useAngularBasedHttpClientInAlfrescoJs: boolean;
}
const defaultConfig: Config = { useAngularBasedHttpClientInAlfrescoJs: false };
@NgModule({
imports: [
@@ -149,7 +141,7 @@ const defaultConfig: Config = { useAngularBasedHttpClientInAlfrescoJs: false };
]
})
export class CoreModule {
static forRoot(config: Config = defaultConfig): ModuleWithProviders<CoreModule> {
static forRoot(): ModuleWithProviders<CoreModule> {
return {
ngModule: CoreModule,
providers: [
@@ -159,7 +151,7 @@ export class CoreModule {
{
provide: APP_INITIALIZER,
useFactory: loadAppConfig,
deps: [ AppConfigService, StorageService ], multi: true
deps: [ AppConfigService, StorageService, AdfHttpClient ], multi: true
},
{
provide: APP_INITIALIZER,
@@ -180,11 +172,7 @@ export class CoreModule {
useFactory: createAlfrescoApiInstance,
deps: [ AlfrescoApiLoaderService ],
multi: true
},
...(config.useAngularBasedHttpClientInAlfrescoJs
? [{ provide: AlfrescoApiService, useClass: AlfrescoApiServiceWithAngularBasedHttpClient }]
: []
)
}
]
};
}

View File

@@ -24,7 +24,6 @@ import { Router, ActivatedRoute, Params } from '@angular/router';
import { AuthenticationService } from '../../auth/services/authentication.service';
import { TranslationService } from '../../translation/translation.service';
import { UserPreferencesService } from '../../common/services/user-preferences.service';
import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { LoginErrorEvent } from '../models/login-error.event';
import { LoginSubmitEvent } from '../models/login-submit.event';
@@ -136,8 +135,7 @@ export class LoginComponent implements OnInit, OnDestroy {
private appConfig: AppConfigService,
private userPreferences: UserPreferencesService,
private route: ActivatedRoute,
private sanitizer: DomSanitizer,
private alfrescoApiService: AlfrescoApiService
private sanitizer: DomSanitizer
) {
}
@@ -188,7 +186,7 @@ export class LoginComponent implements OnInit, OnDestroy {
}
redirectToImplicitLogin() {
this.alfrescoApiService.getInstance().oauth2Auth.implicitLogin();
this.authService.ssoImplicitLogin();
}
/**

View File

@@ -12,6 +12,6 @@
}
},
"exclude": ["src/test.ts", "**/*.spec.ts", "**/*.test.ts"],
"exclude": ["./test.ts", "**/*.spec.ts", "**/*.test.ts"],
"include": ["**/*.ts"]
}

View File

@@ -3,6 +3,6 @@
"compilerOptions": {
"outDir": "../../dist/out-tsc"
},
"files": ["src/test.ts"],
"files": ["./test.ts"],
"include": ["**/*.spec.ts", "**/*.test.ts", "**/*.d.ts"]
}

View File

@@ -24,20 +24,15 @@ import { fakeApplicationInstance, fakeApplicationInstanceWithEnvironment } from
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { fakeEnvironmentList } from '../../common/mock/environment.mock';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('AppsProcessCloudService', () => {
let service: AppsProcessCloudService;
let appConfigService: AppConfigService;
let apiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
const apiMock: any = {
oauth2Auth: {
callCustomApi: () => Promise.resolve({list : { entries: [ {entry: fakeApplicationInstance[0]}, {entry: fakeApplicationInstance[1]}] }})
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
};
const apiMockResponse: any = Promise.resolve({list : { entries: [ {entry: fakeApplicationInstance[0]}, {entry: fakeApplicationInstance[1]}] }});
setupTestBed({
imports: [
@@ -52,8 +47,8 @@ describe('AppsProcessCloudService', () => {
});
beforeEach(() => {
apiService = TestBed.inject(AlfrescoApiService);
spyOn(apiService, 'getInstance').and.returnValue(apiMock);
adfHttpClient = TestBed.inject(AdfHttpClient);
spyOn(adfHttpClient, 'request').and.returnValue(apiMockResponse);
service = TestBed.inject(AppsProcessCloudService);
appConfigService = TestBed.inject(AppConfigService);

View File

@@ -18,10 +18,11 @@
import { Injectable } from '@angular/core';
import { Observable, from, throwError, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { AlfrescoApiService, AppConfigService, LogService } from '@alfresco/adf-core';
import { Oauth2Auth } from '@alfresco/js-api';
import { AppConfigService, LogService } from '@alfresco/adf-core';
import { ApplicationInstanceModel } from '../models/application-instance.model';
import { Environment } from '../../common/interface/environment.interface';
import { AdfHttpClient } from '@alfresco/adf-core/api';
import { RequestOptions } from '@alfresco/js-api';
@Injectable({ providedIn: 'root' })
export class AppsProcessCloudService {
@@ -29,7 +30,7 @@ export class AppsProcessCloudService {
deployedApps: ApplicationInstanceModel[];
constructor(
private apiService: AlfrescoApiService,
private adfHttpClient: AdfHttpClient,
private logService: LogService,
private appConfigService: AppConfigService) {
this.loadApps();
@@ -73,18 +74,28 @@ export class AppsProcessCloudService {
if (status === '') {
return of([]);
}
const api: Oauth2Auth = this.apiService.getInstance().oauth2Auth;
const path = this.getApplicationUrl();
const pathParams = {};
const queryParams = { status, roles : role, sort: 'name' };
const httpMethod = 'GET';
const headerParams = {};
const formParams = {};
const bodyParam = {};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
const requestOptions: RequestOptions = {
path,
pathParams,
queryParams,
headerParams,
formParams,
bodyParam,
contentTypes,
accepts,
httpMethod
};
return from(api.callCustomApi(path, 'GET', pathParams, queryParams, headerParams, formParams, bodyParam,
contentTypes, accepts))
return from(this.adfHttpClient.request(path, requestOptions))
.pipe(
map((applications: any) => applications.list.entries.map((application) => application.entry)),
catchError((err) => this.handleError(err))

View File

@@ -17,24 +17,24 @@
import { TestBed } from '@angular/core/testing';
import { FormCloudService } from './form-cloud.service';
import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { of } from 'rxjs';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { AdfHttpClient } from '@alfresco/adf-core/api';
declare let jasmine: any;
const responseBody = {
const mockTaskResponseBody = {
entry:
{ id: 'id', name: 'name', formKey: 'form-key' }
};
const oauth2Auth = jasmine.createSpyObj('oauth2Auth', ['callCustomApi']);
const mockFormResponseBody = { formRepresentation: { id: 'form-id', name: 'task-form', taskId: 'task-id' } };
describe('Form Cloud service', () => {
let service: FormCloudService;
let apiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
const appName = 'app-name';
const taskId = 'task-id';
const processInstanceId = 'process-instance-id';
@@ -48,26 +48,21 @@ describe('Form Cloud service', () => {
beforeEach(() => {
service = TestBed.inject(FormCloudService);
apiService = TestBed.inject(AlfrescoApiService);
spyOn(apiService, 'getInstance').and.returnValue({
oauth2Auth,
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
} as any);
adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request');
});
describe('Form tests', () => {
it('should fetch and parse form', (done) => {
const formId = 'form-id';
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve({ formRepresentation: { id: formId, name: 'task-form', taskId: 'task-id' } }));
requestSpy.and.returnValue(Promise.resolve(mockFormResponseBody));
service.getForm(appName, formId).subscribe((result) => {
expect(result).toBeDefined();
expect(result.formRepresentation.id).toBe(formId);
expect(result.formRepresentation.name).toBe('task-form');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/form/v1/forms/${formId}`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET');
expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/form/v1/forms/${formId}`);
expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('GET');
done();
});
});
@@ -85,101 +80,101 @@ describe('Form Cloud service', () => {
describe('Task tests', () => {
it('should fetch and parse task', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(responseBody));
requestSpy.and.returnValue(Promise.resolve(mockTaskResponseBody));
service.getTask(appName, taskId).subscribe((result) => {
expect(result).toBeDefined();
expect(result.id).toBe(responseBody.entry.id);
expect(result.name).toBe(responseBody.entry.name);
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/query/v1/tasks/${taskId}`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET');
expect(result.id).toBe('id');
expect(result.name).toBe('name');
expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/query/v1/tasks/${taskId}`);
expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('GET');
done();
});
});
it('should fetch task variables', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve({
requestSpy.and.returnValue(Promise.resolve({
list: {
entries: [
{
entry: {
serviceName: 'fake-rb',
serviceFullName: 'fake-rb',
serviceVersion: '',
appName: 'fake',
appVersion: '',
serviceType: null,
id: 25,
type: 'string',
name: 'fakeProperty',
createTime: 1556112661342,
lastUpdatedTime: 1556112661342,
executionId: null,
value: 'fakeValue',
markedAsDeleted: false,
processInstanceId: '18e16bc7-6694-11e9-9c1b-0a586460028a',
taskId: '18e192da-6694-11e9-9c1b-0a586460028a',
taskVariable: true
}
entries: [
{
entry: {
serviceName: 'fake-rb',
serviceFullName: 'fake-rb',
serviceVersion: '',
appName: 'fake',
appVersion: '',
serviceType: null,
id: 25,
type: 'string',
name: 'fakeProperty',
createTime: 1556112661342,
lastUpdatedTime: 1556112661342,
executionId: null,
value: 'fakeValue',
markedAsDeleted: false,
processInstanceId: '18e16bc7-6694-11e9-9c1b-0a586460028a',
taskId: '18e192da-6694-11e9-9c1b-0a586460028a',
taskVariable: true
}
}
],
pagination: {
skipCount: 0,
maxItems: 100,
count: 1,
hasMoreItems: false,
totalItems: 1
}
],
pagination: {
skipCount: 0,
maxItems: 100,
count: 1,
hasMoreItems: false,
totalItems: 1
}
}
}));
}));
service.getTaskVariables(appName, taskId).subscribe((result) => {
expect(result).toBeDefined();
expect(result.length).toBe(1);
expect(result[0].name).toBe('fakeProperty');
expect(result[0].value).toBe('fakeValue');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/query/v1/tasks/${taskId}/variables`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET');
expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/query/v1/tasks/${taskId}/variables`);
expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('GET');
done();
});
});
it('should fetch result if the variable value is 0', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve({
requestSpy.and.returnValue(Promise.resolve({
list: {
entries: [
{
entry: {
serviceName: 'fake-rb',
serviceFullName: 'fake-rb',
serviceVersion: '',
appName: 'fake',
appVersion: '',
serviceType: null,
id: 25,
type: 'string',
name: 'fakeProperty',
createTime: 1556112661342,
lastUpdatedTime: 1556112661342,
executionId: null,
value: 0,
markedAsDeleted: false,
processInstanceId: '18e16bc7-6694-11e9-9c1b-0a586460028a',
taskId: '18e192da-6694-11e9-9c1b-0a586460028a',
taskVariable: true
}
entries: [
{
entry: {
serviceName: 'fake-rb',
serviceFullName: 'fake-rb',
serviceVersion: '',
appName: 'fake',
appVersion: '',
serviceType: null,
id: 25,
type: 'string',
name: 'fakeProperty',
createTime: 1556112661342,
lastUpdatedTime: 1556112661342,
executionId: null,
value: 0,
markedAsDeleted: false,
processInstanceId: '18e16bc7-6694-11e9-9c1b-0a586460028a',
taskId: '18e192da-6694-11e9-9c1b-0a586460028a',
taskVariable: true
}
}
],
pagination: {
skipCount: 0,
maxItems: 100,
count: 1,
hasMoreItems: false,
totalItems: 1
}
],
pagination: {
skipCount: 0,
maxItems: 100,
count: 1,
hasMoreItems: false,
totalItems: 1
}
}
}));
}));
service.getTaskVariables(appName, taskId).subscribe((result) => {
expect(result).toBeDefined();
@@ -191,7 +186,7 @@ describe('Form Cloud service', () => {
});
it('should fetch task form flattened', (done) => {
spyOn(service, 'getTask').and.returnValue(of(responseBody.entry));
spyOn(service, 'getTask').and.returnValue(of(mockTaskResponseBody.entry));
spyOn(service, 'getForm').and.returnValue(of({
formRepresentation: {
name: 'task-form',
@@ -202,40 +197,40 @@ describe('Form Cloud service', () => {
service.getTaskForm(appName, taskId).subscribe((result) => {
expect(result).toBeDefined();
expect(result.name).toBe('task-form');
expect(result.taskId).toBe(responseBody.entry.id);
expect(result.taskName).toBe(responseBody.entry.name);
expect(result.taskId).toBe('id');
expect(result.taskName).toBe('name');
done();
});
});
it('should save task form', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(responseBody));
requestSpy.and.returnValue(Promise.resolve(mockTaskResponseBody));
const formId = 'form-id';
service.saveTaskForm(appName, taskId, processInstanceId, formId, {}).subscribe((result: any) => {
expect(result).toBeDefined();
expect(result.id).toBe('id');
expect(result.name).toBe('name');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/form/v1/forms/${formId}/save`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('POST');
expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/form/v1/forms/${formId}/save`);
expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('POST');
done();
});
});
it('should complete task form', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(responseBody));
requestSpy.and.returnValue(Promise.resolve(mockTaskResponseBody));
const formId = 'form-id';
service.completeTaskForm(appName, taskId, processInstanceId, formId, {}, '', 1).subscribe((result: any) => {
expect(result).toBeDefined();
expect(result.id).toBe('id');
expect(result.name).toBe('name');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/form/v1/forms/${formId}/submit/versions/1`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('POST');
expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/form/v1/forms/${formId}/submit/versions/1`);
expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('POST');
done();
});
});
});
});
});

View File

@@ -25,6 +25,7 @@ import { TaskVariableCloud } from '../models/task-variable-cloud.model';
import { BaseCloudService } from '../../services/base-cloud.service';
import { FormContent } from '../../services/form-fields.interfaces';
import { FormCloudServiceInterface } from './form-cloud.service.interface';
import { AdfHttpClient } from '@alfresco/adf-core/api';
@Injectable({
providedIn: 'root'
@@ -37,8 +38,10 @@ export class FormCloudService extends BaseCloudService implements FormCloudServi
return this._uploadApi;
}
constructor() {
super();
constructor(
adfHttpClient: AdfHttpClient
) {
super(adfHttpClient);
}
/**

View File

@@ -16,20 +16,17 @@
*/
import { TestBed } from '@angular/core/testing';
import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { FormDefinitionSelectorCloudService } from './form-definition-selector-cloud.service';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { mockFormRepresentations } from '../mocks/form-representation.mock';
declare let jasmine: any;
const oauth2Auth = jasmine.createSpyObj('oauth2Auth', ['callCustomApi', 'on']);
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('Form Definition Selector Cloud Service', () => {
let service: FormDefinitionSelectorCloudService;
let apiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
const appName = 'app-name';
setupTestBed({
@@ -41,17 +38,11 @@ describe('Form Definition Selector Cloud Service', () => {
beforeEach(() => {
service = TestBed.inject(FormDefinitionSelectorCloudService);
apiService = TestBed.inject(AlfrescoApiService);
spyOn(apiService, 'getInstance').and.returnValue({
oauth2Auth,
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
} as any);
adfHttpClient = TestBed.inject(AdfHttpClient);
spyOn(adfHttpClient, 'request').and.returnValue(Promise.resolve(mockFormRepresentations));
});
it('should fetch all the forms when getForms is called', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(mockFormRepresentations));
service.getForms(appName).subscribe((result) => {
expect(result).toBeDefined();
expect(result.length).toBe(3);
@@ -60,8 +51,6 @@ describe('Form Definition Selector Cloud Service', () => {
});
it('should fetch only standalone enabled forms when getStandaloneTaskForms is called', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(mockFormRepresentations));
service.getStandAloneTaskForms(appName).subscribe((result) => {
expect(result).toBeDefined();
expect(result.length).toBe(2);

View File

@@ -16,8 +16,6 @@
*/
import { HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { IdentityGroupModel } from '../models/identity-group.model';
import { IdentityGroupFilterInterface } from '../services/identity-group-filter.interface';
export const mockSearchGroupByRoles: IdentityGroupFilterInterface = {
@@ -35,23 +33,7 @@ export const mockSearchGroupByApp: IdentityGroupFilterInterface = {
withinApplication: 'fake-app-name'
};
export function oAuthMockApiWithIdentityGroups(groups: IdentityGroupModel[]) {
return {
oauth2Auth: {
callCustomApi: () => Promise.resolve(groups)
},
reply: jasmine.createSpy('reply')
};
}
const errorResponse = new HttpErrorResponse({
export const mockHttpErrorResponse = new HttpErrorResponse({
error: 'Mock Error',
status: 404, statusText: 'Not Found'
});
export const oAuthMockApiWithError = {
oauth2Auth: {
callCustomApi: () => throwError(errorResponse)
},
reply: jasmine.createSpy('reply')
};

View File

@@ -17,22 +17,23 @@
import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { IdentityGroupService } from './identity-group.service';
import {
mockHttpErrorResponse,
mockSearchGroupByApp,
mockSearchGroupByRoles,
mockSearchGroupByRolesAndApp,
oAuthMockApiWithError,
oAuthMockApiWithIdentityGroups
mockSearchGroupByRolesAndApp
} from '../mock/identity-group.service.mock';
import { mockFoodGroups } from '../mock/group-cloud.mock';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('IdentityGroupService', () => {
let service: IdentityGroupService;
let alfrescoApiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
setupTestBed({
imports: [
@@ -43,13 +44,14 @@ describe('IdentityGroupService', () => {
beforeEach(() => {
service = TestBed.inject(IdentityGroupService);
alfrescoApiService = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request');
});
describe('Search', () => {
it('should fetch groups', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityGroups(mockFoodGroups )as any);
requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake').subscribe(
@@ -65,7 +67,7 @@ describe('IdentityGroupService', () => {
});
it('should not fetch groups if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError as any);
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
const searchSpy = spyOn(service, 'search').and.callThrough();
@@ -85,7 +87,7 @@ describe('IdentityGroupService', () => {
});
it('should fetch groups by roles', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityGroups(mockFoodGroups) as any);
requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchGroupByRoles).subscribe(
@@ -102,7 +104,7 @@ describe('IdentityGroupService', () => {
});
it('should not fetch groups by roles if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError as any);
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchGroupByRoles)
@@ -125,7 +127,7 @@ describe('IdentityGroupService', () => {
});
it('should fetch groups within app', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityGroups(mockFoodGroups) as any);
requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
service.search('fake', mockSearchGroupByApp).subscribe(
res => {
@@ -140,7 +142,7 @@ describe('IdentityGroupService', () => {
});
it('should fetch groups within app with roles', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityGroups(mockFoodGroups) as any);
requestSpy.and.returnValue(Promise.resolve(mockFoodGroups));
service.search('fake', mockSearchGroupByRolesAndApp).subscribe(
res => {
@@ -156,7 +158,7 @@ describe('IdentityGroupService', () => {
});
it('should not fetch groups within app if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError as any);
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchGroupByApp)

View File

@@ -16,8 +16,6 @@
*/
import { HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { IdentityUserModel } from '../models/identity-user.model';
import { IdentityUserFilterInterface } from '../services/identity-user-filter.interface';
export const mockSearchUserEmptyFilters: IdentityUserFilterInterface = {
@@ -68,23 +66,7 @@ export const mockSearchUserByAppAndGroups: IdentityUserFilterInterface = {
withinApplication: 'fake-app-name'
};
export function oAuthMockApiWithIdentityUsers(users: IdentityUserModel[]) {
return {
oauth2Auth: {
callCustomApi: () => Promise.resolve(users)
},
reply: jasmine.createSpy('reply')
} as any;
}
const errorResponse = new HttpErrorResponse({
export const mockHttpErrorResponse = new HttpErrorResponse({
error: 'Mock Error',
status: 404, statusText: 'Not Found'
});
export const oAuthMockApiWithError = {
oauth2Auth: {
callCustomApi: () => throwError(errorResponse)
},
reply: jasmine.createSpy('reply')
} as any;

View File

@@ -17,7 +17,7 @@
import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { AlfrescoApiService, JwtHelperService, setupTestBed } from '@alfresco/adf-core';
import { JwtHelperService, setupTestBed } from '@alfresco/adf-core';
import { IdentityUserService } from './identity-user.service';
import { mockToken } from '../mock/jwt-helper.service.spec';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
@@ -28,16 +28,17 @@ import {
mockSearchUserByGroupsAndRoles,
mockSearchUserByGroupsAndRolesAndApp,
mockSearchUserByRoles,
mockSearchUserByRolesAndApp,
oAuthMockApiWithError,
oAuthMockApiWithIdentityUsers
mockSearchUserByRolesAndApp
} from '../mock/identity-user.service.mock';
import { mockFoodUsers } from '../mock/people-cloud.mock';
import { AdfHttpClient } from '@alfresco/adf-core/api';
import { mockHttpErrorResponse } from '../../group/mock/identity-group.service.mock';
describe('IdentityUserService', () => {
let service: IdentityUserService;
let alfrescoApiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
setupTestBed({
imports: [
@@ -48,7 +49,8 @@ describe('IdentityUserService', () => {
beforeEach(() => {
service = TestBed.inject(IdentityUserService);
alfrescoApiService = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request');
});
describe('Current user info (JWT token)', () => {
@@ -85,7 +87,7 @@ describe('IdentityUserService', () => {
describe('Search', () => {
it('should fetch users', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake').subscribe(
@@ -101,7 +103,7 @@ describe('IdentityUserService', () => {
});
it('should not fetch users if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError as any);
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
const searchSpy = spyOn(service, 'search').and.callThrough();
@@ -121,7 +123,7 @@ describe('IdentityUserService', () => {
});
it('should fetch users by roles', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByRoles).subscribe(
@@ -138,7 +140,7 @@ describe('IdentityUserService', () => {
});
it('should not fetch users by roles if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError);
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
service.search('fake', mockSearchUserByRoles)
.subscribe(
@@ -155,7 +157,7 @@ describe('IdentityUserService', () => {
});
it('should fetch users by groups', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByGroups).subscribe(
@@ -172,7 +174,7 @@ describe('IdentityUserService', () => {
});
it('should fetch users by roles with groups', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByGroupsAndRoles).subscribe(
@@ -190,7 +192,7 @@ describe('IdentityUserService', () => {
});
it('should fetch users by roles with groups and appName', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByGroupsAndRolesAndApp).subscribe(
@@ -209,7 +211,7 @@ describe('IdentityUserService', () => {
});
it('should not fetch users by groups if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError);
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
service.search('fake', mockSearchUserByGroups)
.subscribe(
@@ -226,7 +228,7 @@ describe('IdentityUserService', () => {
});
it('should fetch users within app', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
service.search('fake', mockSearchUserByApp).subscribe(
res => {
@@ -241,7 +243,7 @@ describe('IdentityUserService', () => {
});
it('should fetch users within app with roles', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
service.search('fake', mockSearchUserByRolesAndApp).subscribe(
res => {
@@ -257,7 +259,7 @@ describe('IdentityUserService', () => {
});
it('should fetch users within app with groups', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithIdentityUsers(mockFoodUsers));
requestSpy.and.returnValue(Promise.resolve(mockFoodUsers));
const searchSpy = spyOn(service, 'search').and.callThrough();
service.search('fake', mockSearchUserByAppAndGroups).subscribe(
@@ -275,7 +277,7 @@ describe('IdentityUserService', () => {
});
it('should not fetch users within app if error occurred', (done) => {
spyOn(alfrescoApiService, 'getInstance').and.returnValue(oAuthMockApiWithError);
requestSpy.and.returnValue(Promise.reject(mockHttpErrorResponse));
service.search('fake', mockSearchUserByApp)
.subscribe(

View File

@@ -16,42 +16,24 @@
*/
import { fakeAsync, TestBed } from '@angular/core/testing';
import { setupTestBed, AlfrescoApiService } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { ProcessListCloudService } from './process-list-cloud.service';
import { ProcessQueryCloudRequestModel } from '../models/process-cloud-query-request.model';
import { ProcessServiceCloudTestingModule } from '../../../testing/process-service-cloud.testing.module';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('ProcessListCloudService', () => {
let service: ProcessListCloudService;
let alfrescoApiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
const returnCallQueryParameters = (): any => ({
oauth2Auth: {
callCustomApi: (_queryUrl, _operation, _context, queryParams) => Promise.resolve(queryParams)
},
isEcmLoggedIn: () => false
});
const returnCallQueryParameters = (_queryUrl, options) => Promise.resolve(options.queryParams);
const returnCallUrl = (): any => ({
oauth2Auth: {
callCustomApi: (queryUrl) => Promise.resolve(queryUrl)
},
isEcmLoggedIn: () => false
});
const returnCallUrl = (queryUrl) => Promise.resolve(queryUrl);
const returnCallOperation = (): any => ({
oauth2Auth: {
callCustomApi: (_queryUrl, operation, _context, _queryParams) => Promise.resolve(operation)
},
isEcmLoggedIn: () => false
});
const returnCallOperation = (_queryUrl, options) => Promise.resolve(options);
const returnCallBody = (): any => ({
oauth2Auth: {
callCustomApi: (_queryUrl, _operation, _context, _queryParams, _headerParams, _formParams, bodyParam) => Promise.resolve(bodyParam)
},
isEcmLoggedIn: () => false
});
const returnCallBody = (_queryUrl, options) => Promise.resolve(options.bodyParam);
setupTestBed({
imports: [
@@ -60,13 +42,14 @@ describe('ProcessListCloudService', () => {
});
beforeEach(fakeAsync(() => {
alfrescoApiService = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
service = TestBed.inject(ProcessListCloudService);
requestSpy = spyOn(adfHttpClient, 'request');
}));
it('should append to the call all the parameters', (done) => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
service.getProcessByRequest(processRequest).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -79,7 +62,7 @@ describe('ProcessListCloudService', () => {
it('should concat the app name to the request url', (done) => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
service.getProcessByRequest(processRequest).subscribe((requestUrl) => {
expect(requestUrl).toBeDefined();
expect(requestUrl).not.toBeNull();
@@ -93,7 +76,7 @@ describe('ProcessListCloudService', () => {
appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service',
sorting: [{ orderBy: 'NAME', direction: 'DESC' }, { orderBy: 'TITLE', direction: 'ASC' }]
} as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
service.getProcessByRequest(processRequest).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -104,7 +87,7 @@ describe('ProcessListCloudService', () => {
it('should return an error when app name is not specified', (done) => {
const processRequest = { appName: null } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
service.getProcessByRequest(processRequest).subscribe(
() => { },
(error) => {
@@ -118,7 +101,7 @@ describe('ProcessListCloudService', () => {
it('should append to the call all the parameters', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
const request = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(request).toBeDefined();
@@ -130,7 +113,7 @@ describe('ProcessListCloudService', () => {
it('should concat the app name to the request url', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
const requestUrl = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(requestUrl).toBeDefined();
@@ -143,7 +126,7 @@ describe('ProcessListCloudService', () => {
appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service',
sorting: [{ orderBy: 'NAME', direction: 'DESC' }, { orderBy: 'TITLE', direction: 'ASC' }]
} as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
const request = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(request).toBeDefined();
@@ -153,7 +136,7 @@ describe('ProcessListCloudService', () => {
it('should return an error when app name is not specified', async () => {
const processRequest = { appName: null } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
try {
await service.getAdminProcessByRequest(processRequest).toPromise();
@@ -166,16 +149,16 @@ describe('ProcessListCloudService', () => {
it('should make post request', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallOperation);
const requestMethod = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(requestMethod).toBeDefined();
expect(requestMethod).not.toBeNull();
expect(requestMethod).toBe('POST');
requestSpy.and.callFake(returnCallOperation);
const adminProcessResponse = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(adminProcessResponse).toBeDefined();
expect(adminProcessResponse).not.toBeNull();
expect(adminProcessResponse.httpMethod).toBe('POST');
});
it('should not have variable keys as part of query parameters', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service', variableKeys: ['test-one', 'test-two'] } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
const requestParams = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(requestParams).toBeDefined();
@@ -185,7 +168,7 @@ describe('ProcessListCloudService', () => {
it('should send right variable keys as post body', async () => {
const processRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service', variableKeys: ['test-one', 'test-two'] } as ProcessQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallBody);
requestSpy.and.callFake(returnCallBody);
const requestBodyParams = await service.getAdminProcessByRequest(processRequest).toPromise();
expect(requestBodyParams).toBeDefined();

View File

@@ -17,16 +17,17 @@
import { TestBed } from '@angular/core/testing';
import { of, throwError } from 'rxjs';
import { setupTestBed, AlfrescoApiService } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { StartProcessCloudService } from './start-process-cloud.service';
import { fakeProcessPayload } from '../mock/start-process.component.mock';
import { ProcessDefinitionCloud } from '../../../models/process-definition-cloud.model';
import { HttpErrorResponse, HttpClientModule } from '@angular/common/http';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('StartProcessCloudService', () => {
let service: StartProcessCloudService;
let alfrescoApiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
setupTestBed({
imports: [HttpClientModule]
@@ -34,7 +35,7 @@ describe('StartProcessCloudService', () => {
beforeEach(() => {
service = TestBed.inject(StartProcessCloudService);
alfrescoApiService = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
});
it('should be able to create a new process', (done) => {
@@ -105,11 +106,8 @@ describe('StartProcessCloudService', () => {
it('should transform the response into task variables', (done) => {
const appName = 'test-app';
const processDefinitionId = 'processDefinitionId';
const oauth2Auth = jasmine.createSpyObj('oauth2Auth', ['callCustomApi']);
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve({ static1: 'value', static2: 0, static3: true }));
spyOn(alfrescoApiService, 'getInstance').and.returnValue({
oauth2Auth
} as any);
const requestSpy = spyOn(adfHttpClient, 'request');
requestSpy.and.returnValue(Promise.resolve({ static1: 'value', static2: 0, static3: true }));
service.getStartEventFormStaticValuesMapping(appName, processDefinitionId).subscribe((result) => {
expect(result.length).toEqual(3);
@@ -122,8 +120,8 @@ describe('StartProcessCloudService', () => {
expect(result[2].name).toEqual('static3');
expect(result[2].id).toEqual('static3');
expect(result[2].value).toEqual(true);
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/rb/v1/process-definitions/${processDefinitionId}/static-values`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET');
expect(requestSpy.calls.mostRecent().args[0]).toContain(`${appName}/rb/v1/process-definitions/${processDefinitionId}/static-values`);
expect(requestSpy.calls.mostRecent().args[1].httpMethod).toBe('GET');
done();
});
});

View File

@@ -18,35 +18,27 @@
import { AlfrescoApiService, AppConfigService, LogService } from '@alfresco/adf-core';
import { Injectable, inject } from '@angular/core';
import { from, Observable } from 'rxjs';
import { AdfHttpClient } from '@alfresco/adf-core/api';
import { RequestOptions } from '@alfresco/js-api';
export interface CallApiParams {
path: string;
httpMethod: string;
pathParams?: any;
queryParams?: any;
headerParams?: any;
formParams?: any;
bodyParam?: any;
contentTypes?: string[];
accepts?: string[];
returnType?: any;
contextRoot?: string;
responseType?: string;
}
@Injectable()
export class BaseCloudService {
protected apiService = inject(AlfrescoApiService);
protected appConfigService = inject(AppConfigService);
protected logService = inject(LogService);
protected defaultParams: CallApiParams = {
protected defaultParams: RequestOptions = {
path: '',
httpMethod: '',
contentTypes: ['application/json'],
accepts: ['application/json']
};
constructor(
protected adfHttpClient: AdfHttpClient) {}
getBasePath(appName: string): string {
return appName
? `${this.contextRoot}/${appName}`
@@ -55,63 +47,64 @@ export class BaseCloudService {
protected post<T, R>(url: string, data?: T, queryParams?: any): Observable<R> {
return from(
this.callApi<R>({
...this.defaultParams,
path: url,
httpMethod: 'POST',
bodyParam: data,
queryParams
})
this.callApi<R>(
url,
{
...this.defaultParams,
path: url,
httpMethod: 'POST',
bodyParam: data,
queryParams
}
)
);
}
protected put<T, R>(url: string, data?: T): Observable<R> {
return from(
this.callApi<R>({
...this.defaultParams,
path: url,
httpMethod: 'PUT',
bodyParam: data
})
this.callApi<R>(
url,
{
...this.defaultParams,
path: url,
httpMethod: 'PUT',
bodyParam: data
}
)
);
}
protected delete(url: string): Observable<void> {
return from(
this.callApi<void>({
...this.defaultParams,
path: url,
httpMethod: 'DELETE'
})
this.callApi<void>(
url,
{
...this.defaultParams,
path: url,
httpMethod: 'DELETE'
}
)
);
}
protected get<T>(url: string, queryParams?: any): Observable<T> {
return from(
this.callApi<T>({
...this.defaultParams,
path: url,
httpMethod: 'GET',
queryParams
})
this.callApi<T>(
url,
{
...this.defaultParams,
path: url,
httpMethod: 'GET',
queryParams
}
)
);
}
protected callApi<T>(params: CallApiParams): Promise<T> {
return this.apiService.getInstance()
.oauth2Auth.callCustomApi(
params.path,
params.httpMethod,
params.pathParams,
params.queryParams,
params.headerParams,
params.formParams,
params.bodyParam,
params.contentTypes,
params.accepts,
params.returnType,
params.contextRoot,
params.responseType
protected callApi<T>(url: string, params: RequestOptions): Promise<T> {
return this.adfHttpClient.request(
url,
params
);
}

View File

@@ -16,7 +16,7 @@
*/
import { TestBed } from '@angular/core/testing';
import { AlfrescoApiService, setupTestBed } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { ProcessServiceCloudTestingModule } from '../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { NotificationCloudService } from './notification-cloud.service';
@@ -27,7 +27,7 @@ describe('NotificationCloudService', () => {
let apollo: Apollo;
let apolloCreateSpy: jasmine.Spy;
let apolloSubscribeSpy: jasmine.Spy;
let apiService: AlfrescoApiService;
const useMock: any = {
subscribe: () => {}
};
@@ -43,14 +43,6 @@ describe('NotificationCloudService', () => {
}
`;
const apiServiceMock: any = {
oauth2Auth: {
token: '1234567'
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
};
setupTestBed({
imports: [
TranslateModule.forRoot(),
@@ -61,9 +53,7 @@ describe('NotificationCloudService', () => {
beforeEach(() => {
service = TestBed.inject(NotificationCloudService);
apollo = TestBed.inject(Apollo);
apiService = TestBed.inject(AlfrescoApiService);
spyOn(apiService, 'getInstance').and.returnValue(apiServiceMock);
service.appsListening = [];
apolloCreateSpy = spyOn(apollo, 'createNamed');
apolloSubscribeSpy = spyOn(apollo, 'use').and.returnValue(useMock);

View File

@@ -22,7 +22,9 @@ import { WebSocketLink } from '@apollo/client/link/ws';
import { onError } from '@apollo/client/link/error';
import { getMainDefinition } from '@apollo/client/utilities';
import { Injectable } from '@angular/core';
import { AuthenticationService } from '@alfresco/adf-core';
import { BaseCloudService } from './base-cloud.service';
import { AdfHttpClient } from '@alfresco/adf-core/api';
@Injectable({
providedIn: 'root'
@@ -30,8 +32,12 @@ import { BaseCloudService } from './base-cloud.service';
export class NotificationCloudService extends BaseCloudService {
appsListening = [];
constructor(public apollo: Apollo, private http: HttpLink) {
super();
constructor(
public apollo: Apollo,
private http: HttpLink,
private authService: AuthenticationService,
protected adfHttpClient: AdfHttpClient) {
super(adfHttpClient);
}
private get webSocketHost() {
@@ -57,7 +63,7 @@ export class NotificationCloudService extends BaseCloudService {
connectionParams: {
kaInterval: 2000,
// eslint-disable-next-line @typescript-eslint/naming-convention
'X-Authorization': 'Bearer ' + this.apiService.getInstance().oauth2Auth.token
'X-Authorization': 'Bearer ' + this.authService.getToken()
}
}
});
@@ -81,7 +87,7 @@ export class NotificationCloudService extends BaseCloudService {
headers: {
...oldHeaders,
// eslint-disable-next-line @typescript-eslint/naming-convention
'X-Authorization': 'Bearer ' + this.apiService.getInstance().oauth2Auth.token
'X-Authorization': 'Bearer ' + this.authService.getToken()
}
});
forward(operation);

View File

@@ -17,36 +17,22 @@
import { TestBed } from '@angular/core/testing';
import { UserPreferenceCloudService } from './user-preference-cloud.service';
import { setupTestBed, AlfrescoApiService } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { mockPreferences, getMockPreference, createMockPreference, updateMockPreference } from '../mock/user-preference.mock';
import { ProcessServiceCloudTestingModule } from '../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('PreferenceService', () => {
let service: UserPreferenceCloudService;
let alfrescoApiMock: AlfrescoApiService;
let getInstanceSpy: jasmine.Spy;
let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
const errorResponse = {
error: 'Mock Error',
state: 404, stateText: 'Not Found'
};
const apiMock = (mockResponse): any => ({
oauth2Auth: {
callCustomApi: () => Promise.resolve(mockResponse)
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
});
const apiErrorMock: any = {
oauth2Auth: {
callCustomApi: () => Promise.reject(errorResponse)
},
isEcmLoggedIn:() => false
};
setupTestBed({
imports: [
TranslateModule.forRoot(),
@@ -56,8 +42,8 @@ describe('PreferenceService', () => {
beforeEach(() => {
service = TestBed.inject(UserPreferenceCloudService);
alfrescoApiMock = TestBed.inject(AlfrescoApiService);
getInstanceSpy = spyOn(alfrescoApiMock, 'getInstance').and.returnValue(apiMock(mockPreferences));
adfHttpClient = TestBed.inject(AdfHttpClient);
requestSpy = spyOn(adfHttpClient, 'request').and.returnValue(Promise.resolve(mockPreferences));
});
it('should return the preferences', (done) => {
@@ -81,7 +67,7 @@ describe('PreferenceService', () => {
});
it('Should not fetch preferences if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock);
requestSpy.and.returnValue(Promise.reject(errorResponse));
service.getPreferences('mock-app-name')
.subscribe(
() => fail('expected an error, not preferences'),
@@ -95,7 +81,7 @@ describe('PreferenceService', () => {
});
it('should return the preference by key', (done) => {
getInstanceSpy.and.returnValue(apiMock(getMockPreference));
requestSpy.and.returnValue(Promise.resolve(getMockPreference));
service.getPreferenceByKey('mock-app-name', 'mock-preference-key').subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -109,7 +95,7 @@ describe('PreferenceService', () => {
});
it('Should not fetch preference by key if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock);
requestSpy.and.returnValue(Promise.reject(errorResponse));
service.getPreferenceByKey('mock-app-name', 'mock-preference-key')
.subscribe(
() => fail('expected an error, not preference'),
@@ -123,7 +109,7 @@ describe('PreferenceService', () => {
});
it('should create preference', (done) => {
getInstanceSpy.and.returnValue(apiMock(createMockPreference));
requestSpy.and.returnValue(Promise.resolve(createMockPreference));
service.createPreference('mock-app-name', 'mock-preference-key', createMockPreference).subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -135,7 +121,7 @@ describe('PreferenceService', () => {
});
it('Should not create preference if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock);
requestSpy.and.returnValue(Promise.reject(errorResponse));
service.createPreference('mock-app-name', 'mock-preference-key', createMockPreference)
.subscribe(
() => fail('expected an error, not to create preference'),
@@ -149,7 +135,7 @@ describe('PreferenceService', () => {
});
it('should update preference', (done) => {
getInstanceSpy.and.returnValue(apiMock(updateMockPreference));
requestSpy.and.returnValue(Promise.resolve(updateMockPreference));
service.updatePreference('mock-app-name', 'mock-preference-key', updateMockPreference).subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -161,7 +147,7 @@ describe('PreferenceService', () => {
});
it('Should not update preference if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock);
requestSpy.and.returnValue(Promise.reject(errorResponse));
service.createPreference('mock-app-name', 'mock-preference-key', updateMockPreference)
.subscribe(
() => fail('expected an error, not to update preference'),
@@ -175,7 +161,7 @@ describe('PreferenceService', () => {
});
it('should delete preference', (done) => {
getInstanceSpy.and.returnValue(apiMock(''));
requestSpy.and.returnValue(Promise.resolve(''));
service.deletePreference('mock-app-name', 'mock-preference-key').subscribe((res: any) => {
expect(res).toBeDefined();
done();
@@ -183,7 +169,7 @@ describe('PreferenceService', () => {
});
it('Should not delete preference if error occurred', (done) => {
getInstanceSpy.and.returnValue(apiErrorMock);
requestSpy.and.returnValue(Promise.reject(errorResponse));
service.deletePreference('mock-app-name', 'mock-preference-key')
.subscribe(
() => fail('expected an error, not to delete preference'),

View File

@@ -16,7 +16,7 @@
*/
import { TestBed } from '@angular/core/testing';
import { setupTestBed, TranslationService, AlfrescoApiService } from '@alfresco/adf-core';
import { setupTestBed, TranslationService } from '@alfresco/adf-core';
import { TaskCloudService } from './task-cloud.service';
import { taskCompleteCloudMock } from '../task-header/mocks/fake-complete-task.mock';
import { assignedTaskDetailsCloudMock, createdTaskDetailsCloudMock, emptyOwnerTaskDetailsCloudMock } from '../task-header/mocks/task-details-cloud.mock';
@@ -25,53 +25,25 @@ import { cloudMockUser } from '../start-task/mock/user-cloud.mock';
import { ProcessServiceCloudTestingModule } from '../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { IdentityUserService } from '../../people/services/identity-user.service';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('Task Cloud Service', () => {
let service: TaskCloudService;
let alfrescoApiMock: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let identityUserService: IdentityUserService;
let translateService: TranslationService;
let requestSpy: jasmine.Spy;
const returnFakeTaskCompleteResults = (): any => ({
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.resolve(taskCompleteCloudMock)
},
isEcmLoggedIn: () => false
});
const returnFakeTaskCompleteResults = () => Promise.resolve(taskCompleteCloudMock);
const returnFakeTaskCompleteResultsError = (): any => ({
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.reject(taskCompleteCloudMock)
},
isEcmLoggedIn: () => false
});
const returnFakeTaskCompleteResultsError = () => Promise.reject(taskCompleteCloudMock);
const returnFakeTaskDetailsResults = (): any => ({
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.resolve(fakeTaskDetailsCloud)
},
isEcmLoggedIn: () => false
});
const returnFakeTaskDetailsResults = () => Promise.resolve(fakeTaskDetailsCloud);
const returnFakeCandidateUsersResults = (): any => ({
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.resolve(['mockuser1', 'mockuser2', 'mockuser3'])
},
isEcmLoggedIn: () => false
});
const returnFakeCandidateUsersResults = () => Promise.resolve(['mockuser1', 'mockuser2', 'mockuser3']);
const returnFakeCandidateGroupResults = (): any => ({
reply: () => {},
oauth2Auth: {
callCustomApi : () => Promise.resolve(['mockgroup1', 'mockgroup2', 'mockgroup3'])
},
isEcmLoggedIn: () => false
});
const returnFakeCandidateGroupResults = () => Promise.resolve(['mockgroup1', 'mockgroup2', 'mockgroup3']);
setupTestBed({
imports: [
@@ -81,18 +53,19 @@ describe('Task Cloud Service', () => {
});
beforeEach(() => {
alfrescoApiMock = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
identityUserService = TestBed.inject(IdentityUserService);
translateService = TestBed.inject(TranslationService);
service = TestBed.inject(TaskCloudService);
spyOn(translateService, 'instant').and.callFake((key) => key ? `${key}_translated` : null);
spyOn(identityUserService, 'getCurrentUserInfo').and.returnValue(cloudMockUser);
requestSpy = spyOn(adfHttpClient, 'request');
});
it('should complete a task', (done) => {
const appName = 'simple-app';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskCompleteResults);
requestSpy.and.callFake(returnFakeTaskCompleteResults);
service.completeTask(appName, taskId).subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -103,7 +76,7 @@ describe('Task Cloud Service', () => {
});
it('should not complete a task', (done) => {
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskCompleteResultsError);
requestSpy.and.callFake(returnFakeTaskCompleteResultsError);
const appName = 'simple-app';
const taskId = '68d54a8f';
@@ -140,7 +113,7 @@ describe('Task Cloud Service', () => {
const appName = 'simple-app';
const taskId = '68d54a8f';
const canCompleteTaskResult = service.canCompleteTask(emptyOwnerTaskDetailsCloudMock);
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskCompleteResults);
requestSpy.and.callFake(returnFakeTaskCompleteResults);
service.completeTask(appName, taskId).subscribe((res: any) => {
expect(canCompleteTaskResult).toEqual(true);
@@ -156,7 +129,7 @@ describe('Task Cloud Service', () => {
const appName = 'taskp-app';
const assignee = 'user12';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.claimTask(appName, taskId, assignee).subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -170,7 +143,7 @@ describe('Task Cloud Service', () => {
const appName = null;
const taskId = '68d54a8f';
const assignee = 'user12';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.claimTask(appName, taskId, assignee).subscribe(
() => { },
(error) => {
@@ -183,7 +156,7 @@ describe('Task Cloud Service', () => {
const appName = 'task-app';
const taskId = null;
const assignee = 'user12';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.claimTask(appName, taskId, assignee).subscribe(
() => { },
(error) => {
@@ -195,7 +168,7 @@ describe('Task Cloud Service', () => {
it('should return the task details when unclaiming a task', (done) => {
const appName = 'taskp-app';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.unclaimTask(appName, taskId).subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -208,7 +181,7 @@ describe('Task Cloud Service', () => {
it('should throw error if appName is not defined when unclaiming a task', (done) => {
const appName = null;
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.unclaimTask(appName, taskId).subscribe(
() => { },
(error) => {
@@ -220,7 +193,7 @@ describe('Task Cloud Service', () => {
it('should throw error if taskId is not defined when unclaiming a task', (done) => {
const appName = 'task-app';
const taskId = null;
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.unclaimTask(appName, taskId).subscribe(
() => { },
(error) => {
@@ -232,7 +205,7 @@ describe('Task Cloud Service', () => {
it('should return the task details when querying by id', (done) => {
const appName = 'taskp-app';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.getTaskById(appName, taskId).subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -245,7 +218,7 @@ describe('Task Cloud Service', () => {
it('should throw error if appName is not defined when querying by id', (done) => {
const appName = null;
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.getTaskById(appName, taskId).subscribe(
() => { },
(error) => {
@@ -257,7 +230,7 @@ describe('Task Cloud Service', () => {
it('should throw error if taskId is not defined when querying by id', (done) => {
const appName = 'task-app';
const taskId = null;
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.getTaskById(appName, taskId).subscribe(
() => { },
(error) => {
@@ -270,7 +243,7 @@ describe('Task Cloud Service', () => {
const appName = null;
const taskId = '68d54a8f';
const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe(
() => { },
(error) => {
@@ -283,7 +256,7 @@ describe('Task Cloud Service', () => {
const appName = 'task-app';
const taskId = null;
const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe(
() => { },
(error) => {
@@ -296,7 +269,7 @@ describe('Task Cloud Service', () => {
const appName = 'taskp-app';
const taskId = '68d54a8f';
const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe((res: any) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -310,7 +283,7 @@ describe('Task Cloud Service', () => {
const appName = null;
const taskId = '68d54a8f';
const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe(
() => { },
(error) => {
@@ -323,7 +296,7 @@ describe('Task Cloud Service', () => {
const appName = 'task-app';
const taskId = null;
const updatePayload = { description: 'New description' };
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.updateTask(appName, taskId, updatePayload).subscribe(
() => { },
(error) => {
@@ -335,7 +308,7 @@ describe('Task Cloud Service', () => {
it('should return the candidate users by appName and taskId', (done) => {
const appName = 'taskp-app';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateUsersResults);
requestSpy.and.callFake(returnFakeCandidateUsersResults);
service.getCandidateUsers(appName, taskId).subscribe((res: string[]) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -349,7 +322,7 @@ describe('Task Cloud Service', () => {
it('should log message and return empty array if appName is not defined when fetching candidate users', (done) => {
const appName = null;
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateUsersResults);
requestSpy.and.callFake(returnFakeCandidateUsersResults);
service.getCandidateUsers(appName, taskId).subscribe(
(res: any[]) => {
expect(res.length).toBe(0);
@@ -360,7 +333,7 @@ describe('Task Cloud Service', () => {
it('should log message and return empty array if taskId is not defined when fetching candidate users', (done) => {
const appName = 'task-app';
const taskId = null;
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateUsersResults);
requestSpy.and.callFake(returnFakeCandidateUsersResults);
service.getCandidateUsers(appName, taskId).subscribe(
(res: any[]) => {
expect(res.length).toBe(0);
@@ -371,7 +344,7 @@ describe('Task Cloud Service', () => {
it('should return the candidate groups by appName and taskId', (done) => {
const appName = 'taskp-app';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateGroupResults);
requestSpy.and.callFake(returnFakeCandidateGroupResults);
service.getCandidateGroups(appName, taskId).subscribe((res: string[]) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -385,7 +358,7 @@ describe('Task Cloud Service', () => {
it('should log message and return empty array if appName is not defined when fetching candidate groups', (done) => {
const appName = null;
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateGroupResults);
requestSpy.and.callFake(returnFakeCandidateGroupResults);
service.getCandidateGroups(appName, taskId).subscribe(
(res: any[]) => {
expect(res.length).toBe(0);
@@ -396,7 +369,7 @@ describe('Task Cloud Service', () => {
it('should log message and return empty array if taskId is not defined when fetching candidate groups', (done) => {
const appName = 'task-app';
const taskId = null;
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeCandidateGroupResults);
requestSpy.and.callFake(returnFakeCandidateGroupResults);
service.getCandidateGroups(appName, taskId).subscribe(
(res: any[]) => {
expect(res.length).toBe(0);
@@ -407,7 +380,7 @@ describe('Task Cloud Service', () => {
it('should call assign api and return updated task details', (done) => {
const appName = 'task-app';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.assign(appName, taskId, 'Phil Woods').subscribe(
(res) => {
expect(res.assignee).toBe('Phil Woods');
@@ -418,7 +391,7 @@ describe('Task Cloud Service', () => {
it('should throw error if appName is not defined when changing task assignee', (done) => {
const appName = '';
const taskId = '68d54a8f';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.assign(appName, taskId, 'mock-assignee').subscribe(
() => { },
(error) => {
@@ -430,7 +403,7 @@ describe('Task Cloud Service', () => {
it('should throw error if taskId is not defined when changing task assignee', (done) => {
const appName = 'task-app';
const taskId = '';
spyOn(alfrescoApiMock, 'getInstance').and.callFake(returnFakeTaskDetailsResults);
requestSpy.and.callFake(returnFakeTaskDetailsResults);
service.assign(appName, taskId, 'mock-assignee').subscribe(
() => { },
(error) => {

View File

@@ -33,6 +33,7 @@ import { ProcessDefinitionCloud } from '../../models/process-definition-cloud.mo
import { DEFAULT_TASK_PRIORITIES, TaskPriorityOption } from '../models/task.model';
import { TaskCloudServiceInterface } from './task-cloud.service.interface';
import { IdentityUserService } from '../../people/services/identity-user.service';
import { AdfHttpClient } from '@alfresco/adf-core/api';
@Injectable({
providedIn: 'root'
@@ -43,9 +44,10 @@ export class TaskCloudService extends BaseCloudService implements TaskCloudServi
constructor(
private translateService: TranslationService,
private identityUserService: IdentityUserService
private identityUserService: IdentityUserService,
adfHttpClient: AdfHttpClient
) {
super();
super(adfHttpClient);
}
/**

View File

@@ -26,6 +26,7 @@ import { TaskCloudNodePaging } from '../../../models/task-cloud.model';
import { NotificationCloudService } from '../../../services/notification-cloud.service';
import { TaskCloudEngineEvent } from '../../../models/engine-event-cloud.model';
import { IdentityUserService } from '../../../people/services/identity-user.service';
import { AdfHttpClient } from '@alfresco/adf-core/api';
const TASK_EVENT_SUBSCRIPTION_QUERY = `
subscription {
@@ -54,8 +55,9 @@ export class TaskFilterCloudService extends BaseCloudService {
private identityUserService: IdentityUserService,
@Inject(TASK_FILTERS_SERVICE_TOKEN)
public preferenceService: PreferenceCloudServiceInterface,
private notificationCloudService: NotificationCloudService) {
super();
private notificationCloudService: NotificationCloudService,
adfHttpClient: AdfHttpClient) {
super(adfHttpClient);
this.filtersSubject = new BehaviorSubject([]);
this.filters$ = this.filtersSubject.asObservable();
}

View File

@@ -296,6 +296,7 @@ describe('TaskFormCloudComponent', () => {
spyOn(component.cancelClick,'emit').and.stub();
fixture.detectChanges();
const cancelBtn = debugElement.query(By.css('#adf-cloud-cancel-task'));
cancelBtn.triggerEventHandler('click', {});
fixture.detectChanges();
@@ -347,7 +348,7 @@ describe('TaskFormCloudComponent', () => {
expect(component.error.emit).toHaveBeenCalled();
});
it('should reload when task is completed', () => {
it('should reload when task is completed', async () => {
spyOn(taskCloudService, 'completeTask').and.returnValue(of({}));
const reloadSpy = spyOn(component, 'ngOnChanges').and.callThrough();
@@ -356,10 +357,11 @@ describe('TaskFormCloudComponent', () => {
const completeBtn = debugElement.query(By.css('[adf-cloud-complete-task]'));
completeBtn.nativeElement.click();
await fixture.whenStable();
expect(reloadSpy).toHaveBeenCalled();
});
it('should reload when task is claimed', () => {
it('should reload when task is claimed', async () => {
spyOn(taskCloudService, 'claimTask').and.returnValue(of({}));
spyOn(component, 'hasCandidateUsers').and.returnValue(true);
const reloadSpy = spyOn(component, 'ngOnChanges').and.callThrough();
@@ -372,10 +374,11 @@ describe('TaskFormCloudComponent', () => {
const claimBtn = debugElement.query(By.css('[adf-cloud-claim-task]'));
claimBtn.nativeElement.click();
await fixture.whenStable();
expect(reloadSpy).toHaveBeenCalled();
});
it('should emit taskUnclaimed when task is unclaimed', () => {
it('should emit taskUnclaimed when task is unclaimed', async () => {
spyOn(taskCloudService, 'unclaimTask').and.returnValue(of({}));
const reloadSpy = spyOn(component, 'ngOnChanges').and.callThrough();
spyOn(component, 'hasCandidateUsers').and.returnValue(true);
@@ -389,6 +392,7 @@ describe('TaskFormCloudComponent', () => {
const unclaimBtn = debugElement.query(By.css('[adf-cloud-unclaim-task]'));
unclaimBtn.nativeElement.click();
await fixture.whenStable();
expect(reloadSpy).toHaveBeenCalled();
});

View File

@@ -16,32 +16,23 @@
*/
import { TestBed } from '@angular/core/testing';
import { setupTestBed, AlfrescoApiService, LogService } from '@alfresco/adf-core';
import { setupTestBed, LogService } from '@alfresco/adf-core';
import { ServiceTaskListCloudService } from './service-task-list-cloud.service';
import { ServiceTaskQueryCloudRequestModel } from '../models/service-task-cloud.model';
import { ProcessServiceCloudTestingModule } from '../../../testing/process-service-cloud.testing.module';
import { of } from 'rxjs';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('Activiti ServiceTaskList Cloud Service', () => {
let service: ServiceTaskListCloudService;
let alfrescoApiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let logService: LogService;
let requestSpy: jasmine.Spy;
const returnCallQueryParameters = (): any => ({
oauth2Auth: {
callCustomApi: (_queryUrl, _operation, _context, queryParams) => Promise.resolve(queryParams)
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
});
const returnCallQueryParameters = (_queryUrl, options) => Promise.resolve(options.queryParams);
const returnCallUrl = (): any => ({
oauth2Auth: {
callCustomApi: (queryUrl) => Promise.resolve(queryUrl)
},
isEcmLoggedIn: () => false
});
const returnCallUrl = (queryUrl) => Promise.resolve(queryUrl);
setupTestBed({
imports: [
@@ -50,14 +41,15 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
});
beforeEach(() => {
alfrescoApiService = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
service = TestBed.inject(ServiceTaskListCloudService);
logService = TestBed.inject(LogService);
requestSpy = spyOn(adfHttpClient, 'request');
});
it('should append to the call all the parameters', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ServiceTaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
service.getServiceTaskByRequest(taskRequest).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -70,7 +62,7 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
it('should concat the app name to the request url', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as ServiceTaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
service.getServiceTaskByRequest(taskRequest).subscribe((requestUrl) => {
expect(requestUrl).toBeDefined();
expect(requestUrl).not.toBeNull();
@@ -84,7 +76,7 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service',
sorting: [{ orderBy: 'NAME', direction: 'DESC' }, { orderBy: 'TITLE', direction: 'ASC' }]
} as ServiceTaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
service.getServiceTaskByRequest(taskRequest).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -95,7 +87,7 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
it('should return an error when app name is not specified', (done) => {
const taskRequest = { appName: null } as ServiceTaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
service.getServiceTaskByRequest(taskRequest).subscribe(
() => { },
(error) => {
@@ -111,7 +103,7 @@ describe('Activiti ServiceTaskList Cloud Service', () => {
beforeEach(() => {
spyOn(service, 'getBasePath').and.returnValue('http://localhost/fakeName');
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
logServiceErrorSpy = spyOn(logService, 'error');
});

View File

@@ -16,31 +16,22 @@
*/
import { TestBed } from '@angular/core/testing';
import { setupTestBed, AlfrescoApiService } from '@alfresco/adf-core';
import { setupTestBed } from '@alfresco/adf-core';
import { TaskListCloudService } from './task-list-cloud.service';
import { TaskQueryCloudRequestModel } from '../../../models/filter-cloud-model';
import { ProcessServiceCloudTestingModule } from '../../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { AdfHttpClient } from '@alfresco/adf-core/api';
describe('TaskListCloudService', () => {
let service: TaskListCloudService;
let alfrescoApiService: AlfrescoApiService;
let adfHttpClient: AdfHttpClient;
let requestSpy: jasmine.Spy;
const returnCallQueryParameters = (): any => ({
oauth2Auth: {
callCustomApi : (_queryUrl, _operation, _context, queryParams) => Promise.resolve(queryParams)
},
isEcmLoggedIn: () => false,
reply: jasmine.createSpy('reply')
});
const returnCallQueryParameters = (_queryUrl, options) => Promise.resolve(options.queryParams);
const returnCallUrl = (): any => ({
oauth2Auth: {
callCustomApi : (queryUrl) => Promise.resolve(queryUrl)
},
isEcmLoggedIn: () => false
});
const returnCallUrl = (queryUrl) => Promise.resolve(queryUrl);
setupTestBed({
imports: [
@@ -50,13 +41,14 @@ describe('TaskListCloudService', () => {
});
beforeEach(() => {
alfrescoApiService = TestBed.inject(AlfrescoApiService);
adfHttpClient = TestBed.inject(AdfHttpClient);
service = TestBed.inject(TaskListCloudService);
requestSpy = spyOn(adfHttpClient, 'request');
});
it('should append to the call all the parameters', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as TaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
service.getTaskByRequest(taskRequest).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -69,7 +61,7 @@ describe('TaskListCloudService', () => {
it('should concat the app name to the request url', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service' } as TaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
service.getTaskByRequest(taskRequest).subscribe((requestUrl) => {
expect(requestUrl).toBeDefined();
expect(requestUrl).not.toBeNull();
@@ -81,7 +73,7 @@ describe('TaskListCloudService', () => {
it('should concat the sorting to append as parameters', (done) => {
const taskRequest = { appName: 'fakeName', skipCount: 0, maxItems: 20, service: 'fake-service',
sorting: [{ orderBy: 'NAME', direction: 'DESC'}, { orderBy: 'TITLE', direction: 'ASC'}] } as TaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallQueryParameters);
requestSpy.and.callFake(returnCallQueryParameters);
service.getTaskByRequest(taskRequest).subscribe((res) => {
expect(res).toBeDefined();
expect(res).not.toBeNull();
@@ -92,7 +84,7 @@ describe('TaskListCloudService', () => {
it('should return an error when app name is not specified', (done) => {
const taskRequest = { appName: null } as TaskQueryCloudRequestModel;
spyOn(alfrescoApiService, 'getInstance').and.callFake(returnCallUrl);
requestSpy.and.callFake(returnCallUrl);
service.getTaskByRequest(taskRequest).subscribe(
() => { },
(error) => {