ESLint: fix indentation

This commit is contained in:
Yury Bondarenko
2023-06-27 16:14:46 +02:00
parent b505cbc690
commit 0690a201dc
410 changed files with 3488 additions and 3488 deletions

View File

@@ -99,7 +99,7 @@ describe('EPeopleRegistryComponent', () => {
deleteEPerson(ePerson: EPerson): Observable<boolean> { deleteEPerson(ePerson: EPerson): Observable<boolean> {
this.allEpeople = this.allEpeople.filter((ePerson2: EPerson) => { this.allEpeople = this.allEpeople.filter((ePerson2: EPerson) => {
return (ePerson2.uuid !== ePerson.uuid); return (ePerson2.uuid !== ePerson.uuid);
}); });
return observableOf(true); return observableOf(true);
}, },
editEPerson(ePerson: EPerson) { editEPerson(ePerson: EPerson) {

View File

@@ -157,34 +157,34 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
} }
this.findListOptionsSub = this.paginationService.getCurrentPagination(this.config.id, this.config).pipe( this.findListOptionsSub = this.paginationService.getCurrentPagination(this.config.id, this.config).pipe(
switchMap((findListOptions) => { switchMap((findListOptions) => {
const query: string = data.query; const query: string = data.query;
const scope: string = data.scope; const scope: string = data.scope;
if (query != null && this.currentSearchQuery !== query) { if (query != null && this.currentSearchQuery !== query) {
this.router.navigate([this.epersonService.getEPeoplePageRouterLink()], { this.router.navigate([this.epersonService.getEPeoplePageRouterLink()], {
queryParamsHandling: 'merge' queryParamsHandling: 'merge'
});
this.currentSearchQuery = query;
this.paginationService.resetPage(this.config.id);
}
if (scope != null && this.currentSearchScope !== scope) {
this.router.navigate([this.epersonService.getEPeoplePageRouterLink()], {
queryParamsHandling: 'merge'
});
this.currentSearchScope = scope;
this.paginationService.resetPage(this.config.id);
}
return this.epersonService.searchByScope(this.currentSearchScope, this.currentSearchQuery, {
currentPage: findListOptions.currentPage,
elementsPerPage: findListOptions.pageSize
}); });
this.currentSearchQuery = query;
this.paginationService.resetPage(this.config.id);
} }
if (scope != null && this.currentSearchScope !== scope) {
this.router.navigate([this.epersonService.getEPeoplePageRouterLink()], {
queryParamsHandling: 'merge'
});
this.currentSearchScope = scope;
this.paginationService.resetPage(this.config.id);
}
return this.epersonService.searchByScope(this.currentSearchScope, this.currentSearchQuery, {
currentPage: findListOptions.currentPage,
elementsPerPage: findListOptions.pageSize
});
}
), ),
getAllSucceededRemoteData(), getAllSucceededRemoteData(),
).subscribe((peopleRD) => { ).subscribe((peopleRD) => {
this.ePeople$.next(peopleRD.payload); this.ePeople$.next(peopleRD.payload);
this.pageInfoState$.next(peopleRD.payload.pageInfo); this.pageInfoState$.next(peopleRD.payload.pageInfo);
} }
); );
} }

View File

@@ -112,60 +112,60 @@ describe('EPersonFormComponent', () => {
createFormGroup(formModel, options = null) { createFormGroup(formModel, options = null) {
const controls = {}; const controls = {};
formModel.forEach( model => { formModel.forEach( model => {
model.parent = parent; model.parent = parent;
const controlModel = model; const controlModel = model;
const controlState = { value: controlModel.value, disabled: controlModel.disabled }; const controlState = { value: controlModel.value, disabled: controlModel.disabled };
const controlOptions = this.createAbstractControlOptions(controlModel.validators, controlModel.asyncValidators, controlModel.updateOn); const controlOptions = this.createAbstractControlOptions(controlModel.validators, controlModel.asyncValidators, controlModel.updateOn);
controls[model.id] = new UntypedFormControl(controlState, controlOptions); controls[model.id] = new UntypedFormControl(controlState, controlOptions);
}); });
return new UntypedFormGroup(controls, options); return new UntypedFormGroup(controls, options);
}, },
createAbstractControlOptions(validatorsConfig = null, asyncValidatorsConfig = null, updateOn = null) { createAbstractControlOptions(validatorsConfig = null, asyncValidatorsConfig = null, updateOn = null) {
return { return {
validators: validatorsConfig !== null ? this.getValidators(validatorsConfig) : null, validators: validatorsConfig !== null ? this.getValidators(validatorsConfig) : null,
}; };
}, },
getValidators(validatorsConfig) { getValidators(validatorsConfig) {
return this.getValidatorFns(validatorsConfig); return this.getValidatorFns(validatorsConfig);
}, },
getValidatorFns(validatorsConfig, validatorsToken = this._NG_VALIDATORS) { getValidatorFns(validatorsConfig, validatorsToken = this._NG_VALIDATORS) {
let validatorFns = []; let validatorFns = [];
if (this.isObject(validatorsConfig)) { if (this.isObject(validatorsConfig)) {
validatorFns = Object.keys(validatorsConfig).map(validatorConfigKey => { validatorFns = Object.keys(validatorsConfig).map(validatorConfigKey => {
const validatorConfigValue = validatorsConfig[validatorConfigKey]; const validatorConfigValue = validatorsConfig[validatorConfigKey];
if (this.isValidatorDescriptor(validatorConfigValue)) { if (this.isValidatorDescriptor(validatorConfigValue)) {
const descriptor = validatorConfigValue; const descriptor = validatorConfigValue;
return this.getValidatorFn(descriptor.name, descriptor.args, validatorsToken); return this.getValidatorFn(descriptor.name, descriptor.args, validatorsToken);
} }
return this.getValidatorFn(validatorConfigKey, validatorConfigValue, validatorsToken); return this.getValidatorFn(validatorConfigKey, validatorConfigValue, validatorsToken);
}); });
} }
return validatorFns; return validatorFns;
}, },
getValidatorFn(validatorName, validatorArgs = null, validatorsToken = this._NG_VALIDATORS) { getValidatorFn(validatorName, validatorArgs = null, validatorsToken = this._NG_VALIDATORS) {
let validatorFn; let validatorFn;
if (Validators.hasOwnProperty(validatorName)) { // Built-in Angular Validators if (Validators.hasOwnProperty(validatorName)) { // Built-in Angular Validators
validatorFn = Validators[validatorName]; validatorFn = Validators[validatorName];
} else { // Custom Validators } else { // Custom Validators
if (this._DYNAMIC_VALIDATORS && this._DYNAMIC_VALIDATORS.has(validatorName)) { if (this._DYNAMIC_VALIDATORS && this._DYNAMIC_VALIDATORS.has(validatorName)) {
validatorFn = this._DYNAMIC_VALIDATORS.get(validatorName); validatorFn = this._DYNAMIC_VALIDATORS.get(validatorName);
} else if (validatorsToken) { } else if (validatorsToken) {
validatorFn = validatorsToken.find(validator => validator.name === validatorName); validatorFn = validatorsToken.find(validator => validator.name === validatorName);
} }
} }
if (validatorFn === undefined) { // throw when no validator could be resolved if (validatorFn === undefined) { // throw when no validator could be resolved
throw new Error(`validator '${validatorName}' is not provided via NG_VALIDATORS, NG_ASYNC_VALIDATORS or DYNAMIC_FORM_VALIDATORS`); throw new Error(`validator '${validatorName}' is not provided via NG_VALIDATORS, NG_ASYNC_VALIDATORS or DYNAMIC_FORM_VALIDATORS`);
} }
if (validatorArgs !== null) { if (validatorArgs !== null) {
return validatorFn(validatorArgs); return validatorFn(validatorArgs);
} }
return validatorFn; return validatorFn;
}, },
isValidatorDescriptor(value) { isValidatorDescriptor(value) {
if (this.isObject(value)) { if (this.isObject(value)) {
return value.hasOwnProperty('name') && value.hasOwnProperty('args'); return value.hasOwnProperty('name') && value.hasOwnProperty('args');
} }
return false; return false;
}, },
isObject(value) { isObject(value) {
return typeof value === 'object' && value !== null; return typeof value === 'object' && value !== null;

View File

@@ -528,14 +528,14 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
if (hasValue(this.epersonInitial.email)) { if (hasValue(this.epersonInitial.email)) {
this.epersonRegistrationService.registerEmail(this.epersonInitial.email, null, TYPE_REQUEST_FORGOT).pipe(getFirstCompletedRemoteData()) this.epersonRegistrationService.registerEmail(this.epersonInitial.email, null, TYPE_REQUEST_FORGOT).pipe(getFirstCompletedRemoteData())
.subscribe((response: RemoteData<Registration>) => { .subscribe((response: RemoteData<Registration>) => {
if (response.hasSucceeded) { if (response.hasSucceeded) {
this.notificationsService.success(this.translateService.get('admin.access-control.epeople.actions.reset'), this.notificationsService.success(this.translateService.get('admin.access-control.epeople.actions.reset'),
this.translateService.get('forgot-email.form.success.content', {email: this.epersonInitial.email})); this.translateService.get('forgot-email.form.success.content', {email: this.epersonInitial.email}));
} else { } else {
this.notificationsService.error(this.translateService.get('forgot-email.form.error.head'), this.notificationsService.error(this.translateService.get('forgot-email.form.error.head'),
this.translateService.get('forgot-email.form.error.content', {email: this.epersonInitial.email})); this.translateService.get('forgot-email.form.error.content', {email: this.epersonInitial.email}));
}
} }
}
); );
} }
} }

View File

@@ -128,60 +128,60 @@ describe('GroupFormComponent', () => {
createFormGroup(formModel, options = null) { createFormGroup(formModel, options = null) {
const controls = {}; const controls = {};
formModel.forEach( model => { formModel.forEach( model => {
model.parent = parent; model.parent = parent;
const controlModel = model; const controlModel = model;
const controlState = { value: controlModel.value, disabled: controlModel.disabled }; const controlState = { value: controlModel.value, disabled: controlModel.disabled };
const controlOptions = this.createAbstractControlOptions(controlModel.validators, controlModel.asyncValidators, controlModel.updateOn); const controlOptions = this.createAbstractControlOptions(controlModel.validators, controlModel.asyncValidators, controlModel.updateOn);
controls[model.id] = new UntypedFormControl(controlState, controlOptions); controls[model.id] = new UntypedFormControl(controlState, controlOptions);
}); });
return new UntypedFormGroup(controls, options); return new UntypedFormGroup(controls, options);
}, },
createAbstractControlOptions(validatorsConfig = null, asyncValidatorsConfig = null, updateOn = null) { createAbstractControlOptions(validatorsConfig = null, asyncValidatorsConfig = null, updateOn = null) {
return { return {
validators: validatorsConfig !== null ? this.getValidators(validatorsConfig) : null, validators: validatorsConfig !== null ? this.getValidators(validatorsConfig) : null,
}; };
}, },
getValidators(validatorsConfig) { getValidators(validatorsConfig) {
return this.getValidatorFns(validatorsConfig); return this.getValidatorFns(validatorsConfig);
}, },
getValidatorFns(validatorsConfig, validatorsToken = this._NG_VALIDATORS) { getValidatorFns(validatorsConfig, validatorsToken = this._NG_VALIDATORS) {
let validatorFns = []; let validatorFns = [];
if (this.isObject(validatorsConfig)) { if (this.isObject(validatorsConfig)) {
validatorFns = Object.keys(validatorsConfig).map(validatorConfigKey => { validatorFns = Object.keys(validatorsConfig).map(validatorConfigKey => {
const validatorConfigValue = validatorsConfig[validatorConfigKey]; const validatorConfigValue = validatorsConfig[validatorConfigKey];
if (this.isValidatorDescriptor(validatorConfigValue)) { if (this.isValidatorDescriptor(validatorConfigValue)) {
const descriptor = validatorConfigValue; const descriptor = validatorConfigValue;
return this.getValidatorFn(descriptor.name, descriptor.args, validatorsToken); return this.getValidatorFn(descriptor.name, descriptor.args, validatorsToken);
} }
return this.getValidatorFn(validatorConfigKey, validatorConfigValue, validatorsToken); return this.getValidatorFn(validatorConfigKey, validatorConfigValue, validatorsToken);
}); });
} }
return validatorFns; return validatorFns;
}, },
getValidatorFn(validatorName, validatorArgs = null, validatorsToken = this._NG_VALIDATORS) { getValidatorFn(validatorName, validatorArgs = null, validatorsToken = this._NG_VALIDATORS) {
let validatorFn; let validatorFn;
if (Validators.hasOwnProperty(validatorName)) { // Built-in Angular Validators if (Validators.hasOwnProperty(validatorName)) { // Built-in Angular Validators
validatorFn = Validators[validatorName]; validatorFn = Validators[validatorName];
} else { // Custom Validators } else { // Custom Validators
if (this._DYNAMIC_VALIDATORS && this._DYNAMIC_VALIDATORS.has(validatorName)) { if (this._DYNAMIC_VALIDATORS && this._DYNAMIC_VALIDATORS.has(validatorName)) {
validatorFn = this._DYNAMIC_VALIDATORS.get(validatorName); validatorFn = this._DYNAMIC_VALIDATORS.get(validatorName);
} else if (validatorsToken) { } else if (validatorsToken) {
validatorFn = validatorsToken.find(validator => validator.name === validatorName); validatorFn = validatorsToken.find(validator => validator.name === validatorName);
} }
} }
if (validatorFn === undefined) { // throw when no validator could be resolved if (validatorFn === undefined) { // throw when no validator could be resolved
throw new Error(`validator '${validatorName}' is not provided via NG_VALIDATORS, NG_ASYNC_VALIDATORS or DYNAMIC_FORM_VALIDATORS`); throw new Error(`validator '${validatorName}' is not provided via NG_VALIDATORS, NG_ASYNC_VALIDATORS or DYNAMIC_FORM_VALIDATORS`);
} }
if (validatorArgs !== null) { if (validatorArgs !== null) {
return validatorFn(validatorArgs); return validatorFn(validatorArgs);
} }
return validatorFn; return validatorFn;
}, },
isValidatorDescriptor(value) { isValidatorDescriptor(value) {
if (this.isObject(value)) { if (this.isObject(value)) {
return value.hasOwnProperty('name') && value.hasOwnProperty('args'); return value.hasOwnProperty('name') && value.hasOwnProperty('args');
} }
return false; return false;
}, },
isObject(value) { isObject(value) {
return typeof value === 'object' && value !== null; return typeof value === 'object' && value !== null;

View File

@@ -77,21 +77,21 @@ export interface EPersonListActionConfig {
export class MembersListComponent implements OnInit, OnDestroy { export class MembersListComponent implements OnInit, OnDestroy {
@Input() @Input()
messagePrefix: string; messagePrefix: string;
@Input() @Input()
actionConfig: EPersonListActionConfig = { actionConfig: EPersonListActionConfig = {
add: { add: {
css: 'btn-outline-primary', css: 'btn-outline-primary',
disabled: false, disabled: false,
icon: 'fas fa-plus fa-fw', icon: 'fas fa-plus fa-fw',
}, },
remove: { remove: {
css: 'btn-outline-danger', css: 'btn-outline-danger',
disabled: false, disabled: false,
icon: 'fas fa-trash-alt fa-fw' icon: 'fas fa-trash-alt fa-fw'
}, },
}; };
/** /**
* EPeople being displayed in search result, initially all members, after search result of search * EPeople being displayed in search result, initially all members, after search result of search
@@ -176,9 +176,9 @@ export class MembersListComponent implements OnInit, OnDestroy {
this.paginationService.getCurrentPagination(this.config.id, this.config).pipe( this.paginationService.getCurrentPagination(this.config.id, this.config).pipe(
switchMap((currentPagination) => { switchMap((currentPagination) => {
return this.ePersonDataService.findListByHref(this.groupBeingEdited._links.epersons.href, { return this.ePersonDataService.findListByHref(this.groupBeingEdited._links.epersons.href, {
currentPage: currentPagination.currentPage, currentPage: currentPagination.currentPage,
elementsPerPage: currentPagination.pageSize elementsPerPage: currentPagination.pageSize
} }
); );
}), }),
getAllCompletedRemoteData(), getAllCompletedRemoteData(),

View File

@@ -40,7 +40,7 @@ enum SubKey {
export class SubgroupsListComponent implements OnInit, OnDestroy { export class SubgroupsListComponent implements OnInit, OnDestroy {
@Input() @Input()
messagePrefix: string; messagePrefix: string;
/** /**
* Result of search groups, initially all groups * Result of search groups, initially all groups
@@ -125,12 +125,12 @@ export class SubgroupsListComponent implements OnInit, OnDestroy {
SubKey.Members, SubKey.Members,
this.paginationService.getCurrentPagination(this.config.id, this.config).pipe( this.paginationService.getCurrentPagination(this.config.id, this.config).pipe(
switchMap((config) => this.groupDataService.findListByHref(this.groupBeingEdited._links.subgroups.href, { switchMap((config) => this.groupDataService.findListByHref(this.groupBeingEdited._links.subgroups.href, {
currentPage: config.currentPage, currentPage: config.currentPage,
elementsPerPage: config.pageSize elementsPerPage: config.pageSize
}, },
true, true,
true, true,
followLink('object') followLink('object')
)) ))
).subscribe((rd: RemoteData<PaginatedList<Group>>) => { ).subscribe((rd: RemoteData<PaginatedList<Group>>) => {
this.subGroups$.next(rd); this.subGroups$.next(rd);

View File

@@ -16,9 +16,9 @@ export class ValidateGroupExists {
static createValidator(groupDataService: GroupDataService) { static createValidator(groupDataService: GroupDataService) {
return (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => { return (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
return groupDataService.searchGroups(control.value, { return groupDataService.searchGroups(control.value, {
currentPage: 1, currentPage: 1,
elementsPerPage: 100 elementsPerPage: 100
}) })
.pipe( .pipe(
getFirstSucceededRemoteListPayload(), getFirstSucceededRemoteListPayload(),
map( (groups: Group[]) => { map( (groups: Group[]) => {

View File

@@ -159,14 +159,14 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy {
]).pipe( ]).pipe(
map(([canDelete, canManageGroup, hasLinkedDSO, subgroups, members]: map(([canDelete, canManageGroup, hasLinkedDSO, subgroups, members]:
[boolean, boolean, boolean, RemoteData<PaginatedList<Group>>, RemoteData<PaginatedList<EPerson>>]) => { [boolean, boolean, boolean, RemoteData<PaginatedList<Group>>, RemoteData<PaginatedList<EPerson>>]) => {
const groupDtoModel: GroupDtoModel = new GroupDtoModel(); const groupDtoModel: GroupDtoModel = new GroupDtoModel();
groupDtoModel.ableToDelete = canDelete && !hasLinkedDSO; groupDtoModel.ableToDelete = canDelete && !hasLinkedDSO;
groupDtoModel.ableToEdit = canManageGroup; groupDtoModel.ableToEdit = canManageGroup;
groupDtoModel.group = group; groupDtoModel.group = group;
groupDtoModel.subgroups = subgroups.payload; groupDtoModel.subgroups = subgroups.payload;
groupDtoModel.epersons = members.payload; groupDtoModel.epersons = members.payload;
return groupDtoModel; return groupDtoModel;
} }
) )
); );
} else { } else {
@@ -185,7 +185,7 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy {
}); });
this.subs.push(this.searchSub); this.subs.push(this.searchSub);
} }
canManageGroup$(isSiteAdmin: boolean, group: Group): Observable<boolean> { canManageGroup$(isSiteAdmin: boolean, group: Group): Observable<boolean> {
if (isSiteAdmin) { if (isSiteAdmin) {
@@ -210,7 +210,7 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy {
this.translateService.get(this.messagePrefix + 'notification.deleted.failure.title', { name: this.dsoNameService.getName(group.group) }), this.translateService.get(this.messagePrefix + 'notification.deleted.failure.title', { name: this.dsoNameService.getName(group.group) }),
this.translateService.get(this.messagePrefix + 'notification.deleted.failure.content', { cause: rd.errorMessage })); this.translateService.get(this.messagePrefix + 'notification.deleted.failure.content', { cause: rd.errorMessage }));
} }
}); });
} }
} }

View File

@@ -35,16 +35,16 @@ export class AddBitstreamFormatComponent {
this.bitstreamFormatDataService.createBitstreamFormat(bitstreamFormat).pipe( this.bitstreamFormatDataService.createBitstreamFormat(bitstreamFormat).pipe(
getFirstCompletedRemoteData(), getFirstCompletedRemoteData(),
).subscribe((response: RemoteData<BitstreamFormat>) => { ).subscribe((response: RemoteData<BitstreamFormat>) => {
if (response.hasSucceeded) { if (response.hasSucceeded) {
this.notificationService.success(this.translateService.get('admin.registries.bitstream-formats.create.success.head'), this.notificationService.success(this.translateService.get('admin.registries.bitstream-formats.create.success.head'),
this.translateService.get('admin.registries.bitstream-formats.create.success.content')); this.translateService.get('admin.registries.bitstream-formats.create.success.content'));
this.router.navigate([getBitstreamFormatsModuleRoute()]); this.router.navigate([getBitstreamFormatsModuleRoute()]);
this.bitstreamFormatDataService.clearBitStreamFormatRequests().subscribe(); this.bitstreamFormatDataService.clearBitStreamFormatRequests().subscribe();
} else { } else {
this.notificationService.error(this.translateService.get('admin.registries.bitstream-formats.create.failure.head'), this.notificationService.error(this.translateService.get('admin.registries.bitstream-formats.create.failure.head'),
this.translateService.get('admin.registries.bitstream-formats.create.failure.content')); this.translateService.get('admin.registries.bitstream-formats.create.failure.content'));
}
} }
}
); );
} }
} }

View File

@@ -212,34 +212,34 @@ describe('BitstreamFormatsComponent', () => {
describe('deleteFormats success', () => { describe('deleteFormats success', () => {
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
notificationsServiceStub = new NotificationsServiceStub(); notificationsServiceStub = new NotificationsServiceStub();
scheduler = getTestScheduler(); scheduler = getTestScheduler();
bitstreamFormatService = jasmine.createSpyObj('bitstreamFormatService', { bitstreamFormatService = jasmine.createSpyObj('bitstreamFormatService', {
findAll: observableOf(mockFormatsRD), findAll: observableOf(mockFormatsRD),
find: createSuccessfulRemoteDataObject$(mockFormatsList[0]), find: createSuccessfulRemoteDataObject$(mockFormatsList[0]),
getSelectedBitstreamFormats: observableOf(mockFormatsList), getSelectedBitstreamFormats: observableOf(mockFormatsList),
selectBitstreamFormat: {}, selectBitstreamFormat: {},
deselectBitstreamFormat: {}, deselectBitstreamFormat: {},
deselectAllBitstreamFormats: {}, deselectAllBitstreamFormats: {},
delete: createNoContentRemoteDataObject$(), delete: createNoContentRemoteDataObject$(),
clearBitStreamFormatRequests: observableOf('cleared') clearBitStreamFormatRequests: observableOf('cleared')
}); });
paginationService = new PaginationServiceStub(); paginationService = new PaginationServiceStub();
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
declarations: [BitstreamFormatsComponent, PaginationComponent, EnumKeysPipe], declarations: [BitstreamFormatsComponent, PaginationComponent, EnumKeysPipe],
providers: [ providers: [
{ provide: BitstreamFormatDataService, useValue: bitstreamFormatService }, { provide: BitstreamFormatDataService, useValue: bitstreamFormatService },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) }, { provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: NotificationsService, useValue: notificationsServiceStub }, { provide: NotificationsService, useValue: notificationsServiceStub },
{ provide: PaginationService, useValue: paginationService } { provide: PaginationService, useValue: paginationService }
] ]
}).compileComponents(); }).compileComponents();
} }
)); ));
beforeEach(initBeforeEach); beforeEach(initBeforeEach);
@@ -261,34 +261,34 @@ describe('BitstreamFormatsComponent', () => {
describe('deleteFormats error', () => { describe('deleteFormats error', () => {
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
notificationsServiceStub = new NotificationsServiceStub(); notificationsServiceStub = new NotificationsServiceStub();
scheduler = getTestScheduler(); scheduler = getTestScheduler();
bitstreamFormatService = jasmine.createSpyObj('bitstreamFormatService', { bitstreamFormatService = jasmine.createSpyObj('bitstreamFormatService', {
findAll: observableOf(mockFormatsRD), findAll: observableOf(mockFormatsRD),
find: createSuccessfulRemoteDataObject$(mockFormatsList[0]), find: createSuccessfulRemoteDataObject$(mockFormatsList[0]),
getSelectedBitstreamFormats: observableOf(mockFormatsList), getSelectedBitstreamFormats: observableOf(mockFormatsList),
selectBitstreamFormat: {}, selectBitstreamFormat: {},
deselectBitstreamFormat: {}, deselectBitstreamFormat: {},
deselectAllBitstreamFormats: {}, deselectAllBitstreamFormats: {},
delete: createFailedRemoteDataObject$(), delete: createFailedRemoteDataObject$(),
clearBitStreamFormatRequests: observableOf('cleared') clearBitStreamFormatRequests: observableOf('cleared')
}); });
paginationService = new PaginationServiceStub(); paginationService = new PaginationServiceStub();
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule],
declarations: [BitstreamFormatsComponent, PaginationComponent, EnumKeysPipe], declarations: [BitstreamFormatsComponent, PaginationComponent, EnumKeysPipe],
providers: [ providers: [
{ provide: BitstreamFormatDataService, useValue: bitstreamFormatService }, { provide: BitstreamFormatDataService, useValue: bitstreamFormatService },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(0) }, { provide: HostWindowService, useValue: new HostWindowServiceStub(0) },
{ provide: NotificationsService, useValue: notificationsServiceStub }, { provide: NotificationsService, useValue: notificationsServiceStub },
{ provide: PaginationService, useValue: paginationService } { provide: PaginationService, useValue: paginationService }
] ]
}).compileComponents(); }).compileComponents();
} }
)); ));
beforeEach(initBeforeEach); beforeEach(initBeforeEach);

View File

@@ -49,15 +49,15 @@ export class EditBitstreamFormatComponent implements OnInit {
this.bitstreamFormatDataService.updateBitstreamFormat(bitstreamFormat).pipe( this.bitstreamFormatDataService.updateBitstreamFormat(bitstreamFormat).pipe(
getFirstCompletedRemoteData(), getFirstCompletedRemoteData(),
).subscribe((response: RemoteData<BitstreamFormat>) => { ).subscribe((response: RemoteData<BitstreamFormat>) => {
if (response.hasSucceeded) { if (response.hasSucceeded) {
this.notificationService.success(this.translateService.get('admin.registries.bitstream-formats.edit.success.head'), this.notificationService.success(this.translateService.get('admin.registries.bitstream-formats.edit.success.head'),
this.translateService.get('admin.registries.bitstream-formats.edit.success.content')); this.translateService.get('admin.registries.bitstream-formats.edit.success.content'));
this.router.navigate([getBitstreamFormatsModuleRoute()]); this.router.navigate([getBitstreamFormatsModuleRoute()]);
} else { } else {
this.notificationService.error('admin.registries.bitstream-formats.edit.failure.head', this.notificationService.error('admin.registries.bitstream-formats.edit.failure.head',
'admin.registries.bitstream-formats.create.edit.content'); 'admin.registries.bitstream-formats.create.edit.content');
}
} }
}
); );
} }
} }

View File

@@ -82,33 +82,33 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy {
this.translateService.get(`${this.messagePrefix}.namespace`) this.translateService.get(`${this.messagePrefix}.namespace`)
]).subscribe(([name, namespace]) => { ]).subscribe(([name, namespace]) => {
this.name = new DynamicInputModel({ this.name = new DynamicInputModel({
id: 'name', id: 'name',
label: name, label: name,
name: 'name', name: 'name',
validators: { validators: {
required: null, required: null,
pattern: '^[^. ,]*$', pattern: '^[^. ,]*$',
maxLength: 32, maxLength: 32,
}, },
required: true, required: true,
errorMessages: { errorMessages: {
pattern: 'error.validation.metadata.name.invalid-pattern', pattern: 'error.validation.metadata.name.invalid-pattern',
maxLength: 'error.validation.metadata.name.max-length', maxLength: 'error.validation.metadata.name.max-length',
}, },
}); });
this.namespace = new DynamicInputModel({ this.namespace = new DynamicInputModel({
id: 'namespace', id: 'namespace',
label: namespace, label: namespace,
name: 'namespace', name: 'namespace',
validators: { validators: {
required: null, required: null,
maxLength: 256, maxLength: 256,
}, },
required: true, required: true,
errorMessages: { errorMessages: {
maxLength: 'error.validation.metadata.namespace.max-length', maxLength: 'error.validation.metadata.namespace.max-length',
}, },
}); });
this.formModel = [ this.formModel = [
new DynamicFormGroupModel( new DynamicFormGroupModel(
{ {

View File

@@ -140,10 +140,10 @@ export class MetadataFieldFormComponent implements OnInit, OnDestroy {
}); });
this.formModel = [ this.formModel = [
new DynamicFormGroupModel( new DynamicFormGroupModel(
{ {
id: 'metadatadatafieldgroup', id: 'metadatadatafieldgroup',
group:[this.element, this.qualifier, this.scopeNote] group:[this.element, this.qualifier, this.scopeNote]
}) })
]; ];
this.formGroup = this.formBuilderService.createFormGroup(this.formModel); this.formGroup = this.formBuilderService.createFormGroup(this.formModel);
this.registryService.getActiveMetadataField().subscribe((field: MetadataField): void => { this.registryService.getActiveMetadataField().subscribe((field: MetadataField): void => {

View File

@@ -30,7 +30,7 @@ describe('SupervisionOrderStatusComponent', () => {
NO_ERRORS_SCHEMA NO_ERRORS_SCHEMA
] ]
}) })
.compileComponents(); .compileComponents();
}); });
beforeEach(() => { beforeEach(() => {

View File

@@ -11,7 +11,7 @@ import { URLCombiner } from '../../../../../core/url-combiner/url-combiner';
import { WorkspaceItemAdminWorkflowActionsComponent } from './workspace-item-admin-workflow-actions.component'; import { WorkspaceItemAdminWorkflowActionsComponent } from './workspace-item-admin-workflow-actions.component';
import { WorkspaceItem } from '../../../../../core/submission/models/workspaceitem.model'; import { WorkspaceItem } from '../../../../../core/submission/models/workspaceitem.model';
import { import {
getWorkspaceItemDeleteRoute, getWorkspaceItemDeleteRoute,
} from '../../../../../workflowitems-edit-page/workflowitems-edit-page-routing-paths'; } from '../../../../../workflowitems-edit-page/workflowitems-edit-page-routing-paths';
import { Item } from '../../../../../core/shared/item.model'; import { Item } from '../../../../../core/shared/item.model';
import { RemoteData } from '../../../../../core/data/remote-data'; import { RemoteData } from '../../../../../core/data/remote-data';

View File

@@ -11,7 +11,7 @@ import {
SupervisionOrderGroupSelectorComponent SupervisionOrderGroupSelectorComponent
} from './supervision-order-group-selector/supervision-order-group-selector.component'; } from './supervision-order-group-selector/supervision-order-group-selector.component';
import { import {
getWorkspaceItemDeleteRoute getWorkspaceItemDeleteRoute
} from '../../../../../workflowitems-edit-page/workflowitems-edit-page-routing-paths'; } from '../../../../../workflowitems-edit-page/workflowitems-edit-page-routing-paths';
import { ITEM_EDIT_AUTHORIZATIONS_PATH } from '../../../../../item-page/edit-item-page/edit-item-page.routing-paths'; import { ITEM_EDIT_AUTHORIZATIONS_PATH } from '../../../../../item-page/edit-item-page/edit-item-page.routing-paths';
import { WorkspaceItem } from '../../../../../core/submission/models/workspaceitem.model'; import { WorkspaceItem } from '../../../../../core/submission/models/workspaceitem.model';

View File

@@ -75,25 +75,25 @@ export class WorkflowItemSearchResultAdminWorkflowGridElementComponent extends S
this.dso = this.linkService.resolveLink(this.dso, followLink('item')); this.dso = this.linkService.resolveLink(this.dso, followLink('item'));
this.item$ = (this.dso.item as Observable<RemoteData<Item>>).pipe(getAllSucceededRemoteData(), getRemoteDataPayload()); this.item$ = (this.dso.item as Observable<RemoteData<Item>>).pipe(getAllSucceededRemoteData(), getRemoteDataPayload());
this.item$.pipe(take(1)).subscribe((item: Item) => { this.item$.pipe(take(1)).subscribe((item: Item) => {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.getComponent(item)); const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.getComponent(item));
const viewContainerRef = this.listableObjectDirective.viewContainerRef; const viewContainerRef = this.listableObjectDirective.viewContainerRef;
viewContainerRef.clear(); viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent( const componentRef = viewContainerRef.createComponent(
componentFactory, componentFactory,
0, 0,
undefined, undefined,
[ [
[this.badges.nativeElement], [this.badges.nativeElement],
[this.buttons.nativeElement] [this.buttons.nativeElement]
]); ]);
(componentRef.instance as any).object = item; (componentRef.instance as any).object = item;
(componentRef.instance as any).index = this.index; (componentRef.instance as any).index = this.index;
(componentRef.instance as any).linkType = this.linkType; (componentRef.instance as any).linkType = this.linkType;
(componentRef.instance as any).listID = this.listID; (componentRef.instance as any).listID = this.listID;
componentRef.changeDetectorRef.detectChanges(); componentRef.changeDetectorRef.detectChanges();
} }
); );
} }

View File

@@ -100,25 +100,25 @@ export class WorkspaceItemSearchResultAdminWorkflowGridElementComponent extends
this.dso = this.linkService.resolveLink(this.dso, followLink('item')); this.dso = this.linkService.resolveLink(this.dso, followLink('item'));
this.item$ = (this.dso.item as Observable<RemoteData<Item>>).pipe(getAllSucceededRemoteData(), getRemoteDataPayload()); this.item$ = (this.dso.item as Observable<RemoteData<Item>>).pipe(getAllSucceededRemoteData(), getRemoteDataPayload());
this.item$.pipe(take(1)).subscribe((item: Item) => { this.item$.pipe(take(1)).subscribe((item: Item) => {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.getComponent(item)); const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.getComponent(item));
const viewContainerRef = this.listableObjectDirective.viewContainerRef; const viewContainerRef = this.listableObjectDirective.viewContainerRef;
viewContainerRef.clear(); viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent( const componentRef = viewContainerRef.createComponent(
componentFactory, componentFactory,
0, 0,
undefined, undefined,
[ [
[this.badges.nativeElement], [this.badges.nativeElement],
[this.buttons.nativeElement] [this.buttons.nativeElement]
]); ]);
(componentRef.instance as any).object = item; (componentRef.instance as any).object = item;
(componentRef.instance as any).index = this.index; (componentRef.instance as any).index = this.index;
(componentRef.instance as any).linkType = this.linkType; (componentRef.instance as any).linkType = this.linkType;
(componentRef.instance as any).listID = this.listID; (componentRef.instance as any).listID = this.listID;
componentRef.changeDetectorRef.detectChanges(); componentRef.changeDetectorRef.detectChanges();
} }
); );
this.item$.pipe( this.item$.pipe(

View File

@@ -248,7 +248,7 @@ import { ThemedPageErrorComponent } from './page-error/themed-page-error.compone
initialNavigation: 'enabledBlocking', initialNavigation: 'enabledBlocking',
preloadingStrategy: NoPreloading, preloadingStrategy: NoPreloading,
onSameUrlNavigation: 'reload', onSameUrlNavigation: 'reload',
}) })
], ],
exports: [RouterModule], exports: [RouterModule],
}) })

View File

@@ -11,7 +11,7 @@ import { getFirstCompletedRemoteData } from '../core/shared/operators';
* The self links defined in this list are expected to be requested somewhere in the near future * The self links defined in this list are expected to be requested somewhere in the near future
* Requesting them as embeds will limit the number of requests * Requesting them as embeds will limit the number of requests
*/ */
export const BITSTREAM_PAGE_LINKS_TO_FOLLOW: FollowLinkConfig<Bitstream>[] = [ export const BITSTREAM_PAGE_LINKS_TO_FOLLOW: FollowLinkConfig<Bitstream>[] = [
followLink('bundle', {}, followLink('primaryBitstream'), followLink('item')), followLink('bundle', {}, followLink('primaryBitstream'), followLink('item')),
followLink('format') followLink('format')
]; ];
@@ -37,12 +37,12 @@ export class BitstreamPageResolver implements Resolve<RemoteData<Bitstream>> {
getFirstCompletedRemoteData(), getFirstCompletedRemoteData(),
); );
} }
/** /**
* Method that returns the follow links to already resolve * Method that returns the follow links to already resolve
* The self links defined in this list are expected to be requested somewhere in the near future * The self links defined in this list are expected to be requested somewhere in the near future
* Requesting them as embeds will limit the number of requests * Requesting them as embeds will limit the number of requests
*/ */
get followLinks(): FollowLinkConfig<Bitstream>[] { get followLinks(): FollowLinkConfig<Bitstream>[] {
return BITSTREAM_PAGE_LINKS_TO_FOLLOW; return BITSTREAM_PAGE_LINKS_TO_FOLLOW;
} }
} }

View File

@@ -129,11 +129,11 @@ describe('EditBitstreamPageComponent', () => {
const result = createSuccessfulRemoteDataObject$(bundle); const result = createSuccessfulRemoteDataObject$(bundle);
primaryBitstreamService = jasmine.createSpyObj('PrimaryBitstreamService', primaryBitstreamService = jasmine.createSpyObj('PrimaryBitstreamService',
{ {
put: result, put: result,
create: result, create: result,
delete: result, delete: result,
}); });
}); });
@@ -535,120 +535,120 @@ describe('EditBitstreamPageComponent', () => {
}); });
}); });
describe('ignore OTHERCONTENT bundle', () => { describe('ignore OTHERCONTENT bundle', () => {
const bundleName = 'OTHERCONTENT'; const bundleName = 'OTHERCONTENT';
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
bitstream = Object.assign(new Bitstream(), { bitstream = Object.assign(new Bitstream(), {
metadata: { metadata: {
'dc.description': [ 'dc.description': [
{ {
value: 'Bitstream description' value: 'Bitstream description'
} }
],
'dc.title': [
{
value: 'Bitstream title'
}
],
'iiif.label': [
{
value: 'chapter one'
}
],
'iiif.toc': [
{
value: 'chapter one'
}
],
'iiif.image.width': [
{
value: '2400'
}
],
'iiif.image.height': [
{
value: '2800'
}
],
},
format: createSuccessfulRemoteDataObject$(allFormats[2]),
_links: {
self: 'bitstream-selflink'
},
bundle: createSuccessfulRemoteDataObject$({
_links: {
primaryBitstream: {
href: 'bundle-selflink'
}
},
item: createSuccessfulRemoteDataObject$(Object.assign(new Item(), {
uuid: 'some-uuid',
firstMetadataValue(keyOrKeys: string | string[], valueFilter?: MetadataValueFilter): string {
return 'True';
}
}))
}),
});
bitstreamService = jasmine.createSpyObj('bitstreamService', {
findById: createSuccessfulRemoteDataObject$(bitstream),
findByHref: createSuccessfulRemoteDataObject$(bitstream),
update: createSuccessfulRemoteDataObject$(bitstream),
updateFormat: createSuccessfulRemoteDataObject$(bitstream),
commitUpdates: {},
patch: {}
});
dsoNameService = jasmine.createSpyObj('dsoNameService', {
getName: bundleName
});
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), RouterTestingModule],
declarations: [EditBitstreamPageComponent, FileSizePipe, VarDirective],
providers: [
{provide: NotificationsService, useValue: notificationsService},
{provide: DynamicFormService, useValue: formService},
{provide: ActivatedRoute,
useValue: {
data: observableOf({bitstream: createSuccessfulRemoteDataObject(bitstream)}),
snapshot: {queryParams: {}}
}
},
{provide: BitstreamDataService, useValue: bitstreamService},
{provide: DSONameService, useValue: dsoNameService},
{provide: BitstreamFormatDataService, useValue: bitstreamFormatService},
{ provide: PrimaryBitstreamService, useValue: primaryBitstreamService },
ChangeDetectorRef
], ],
schemas: [NO_ERRORS_SCHEMA] 'dc.title': [
}).compileComponents(); {
})); value: 'Bitstream title'
}
],
'iiif.label': [
{
value: 'chapter one'
}
],
'iiif.toc': [
{
value: 'chapter one'
}
],
'iiif.image.width': [
{
value: '2400'
}
],
'iiif.image.height': [
{
value: '2800'
}
],
},
format: createSuccessfulRemoteDataObject$(allFormats[2]),
_links: {
self: 'bitstream-selflink'
},
bundle: createSuccessfulRemoteDataObject$({
_links: {
primaryBitstream: {
href: 'bundle-selflink'
}
},
item: createSuccessfulRemoteDataObject$(Object.assign(new Item(), {
uuid: 'some-uuid',
firstMetadataValue(keyOrKeys: string | string[], valueFilter?: MetadataValueFilter): string {
return 'True';
}
}))
}),
});
bitstreamService = jasmine.createSpyObj('bitstreamService', {
findById: createSuccessfulRemoteDataObject$(bitstream),
findByHref: createSuccessfulRemoteDataObject$(bitstream),
update: createSuccessfulRemoteDataObject$(bitstream),
updateFormat: createSuccessfulRemoteDataObject$(bitstream),
commitUpdates: {},
patch: {}
});
dsoNameService = jasmine.createSpyObj('dsoNameService', {
getName: bundleName
});
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), RouterTestingModule],
declarations: [EditBitstreamPageComponent, FileSizePipe, VarDirective],
providers: [
{provide: NotificationsService, useValue: notificationsService},
{provide: DynamicFormService, useValue: formService},
{provide: ActivatedRoute,
useValue: {
data: observableOf({bitstream: createSuccessfulRemoteDataObject(bitstream)}),
snapshot: {queryParams: {}}
}
},
{provide: BitstreamDataService, useValue: bitstreamService},
{provide: DSONameService, useValue: dsoNameService},
{provide: BitstreamFormatDataService, useValue: bitstreamFormatService},
{ provide: PrimaryBitstreamService, useValue: primaryBitstreamService },
ChangeDetectorRef
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(EditBitstreamPageComponent);
comp = fixture.componentInstance;
fixture.detectChanges();
router = TestBed.inject(Router);
spyOn(router, 'navigate');
});
describe('EditBitstreamPageComponent with IIIF fields', () => {
let rawForm;
beforeEach(() => { beforeEach(() => {
fixture = TestBed.createComponent(EditBitstreamPageComponent); rawForm = comp.formGroup.getRawValue();
comp = fixture.componentInstance;
fixture.detectChanges();
router = TestBed.inject(Router);
spyOn(router, 'navigate');
}); });
describe('EditBitstreamPageComponent with IIIF fields', () => { it('should NOT set is IIIF to true', () => {
let rawForm; expect(comp.isIIIF).toBeFalse();
beforeEach(() => {
rawForm = comp.formGroup.getRawValue();
});
it('should NOT set is IIIF to true', () => {
expect(comp.isIIIF).toBeFalse();
});
it('should put the \"IIIF Label\" input not to be shown', () => {
expect(rawForm.iiifLabelContainer).toBeFalsy();
});
}); });
it('should put the \"IIIF Label\" input not to be shown', () => {
expect(rawForm.iiifLabelContainer).toBeFalsy();
});
});
}); });
}); });

View File

@@ -135,9 +135,9 @@ export class EditBitstreamPageComponent implements OnInit, OnDestroy {
* The Dynamic Switch Model for the file's name * The Dynamic Switch Model for the file's name
*/ */
primaryBitstreamModel = new DynamicCustomSwitchModel({ primaryBitstreamModel = new DynamicCustomSwitchModel({
id: 'primaryBitstream', id: 'primaryBitstream',
name: 'primaryBitstream' name: 'primaryBitstream'
} }
); );
/** /**
@@ -170,15 +170,15 @@ export class EditBitstreamPageComponent implements OnInit, OnDestroy {
* The Dynamic Input Model for the iiif label * The Dynamic Input Model for the iiif label
*/ */
iiifLabelModel = new DsDynamicInputModel({ iiifLabelModel = new DsDynamicInputModel({
hasSelectableMetadata: false, metadataFields: [], repeatable: false, submissionId: '', hasSelectableMetadata: false, metadataFields: [], repeatable: false, submissionId: '',
id: 'iiifLabel', id: 'iiifLabel',
name: 'iiifLabel' name: 'iiifLabel'
}, },
{ {
grid: { grid: {
host: 'col col-lg-6 d-inline-block' host: 'col col-lg-6 d-inline-block'
} }
}); });
iiifLabelContainer = new DynamicFormGroupModel({ iiifLabelContainer = new DynamicFormGroupModel({
id: 'iiifLabelContainer', id: 'iiifLabelContainer',
group: [this.iiifLabelModel] group: [this.iiifLabelModel]
@@ -382,7 +382,7 @@ export class EditBitstreamPageComponent implements OnInit, OnDestroy {
private notificationsService: NotificationsService, private notificationsService: NotificationsService,
private bitstreamFormatService: BitstreamFormatDataService, private bitstreamFormatService: BitstreamFormatDataService,
private primaryBitstreamService: PrimaryBitstreamService, private primaryBitstreamService: PrimaryBitstreamService,
) { ) {
} }
/** /**

View File

@@ -28,21 +28,21 @@ export class LegacyBitstreamUrlResolver implements Resolve<RemoteData<Bitstream>
*/ */
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
Observable<RemoteData<Bitstream>> { Observable<RemoteData<Bitstream>> {
const prefix = route.params.prefix; const prefix = route.params.prefix;
const suffix = route.params.suffix; const suffix = route.params.suffix;
const filename = route.params.filename; const filename = route.params.filename;
let sequenceId = route.params.sequence_id; let sequenceId = route.params.sequence_id;
if (hasNoValue(sequenceId)) { if (hasNoValue(sequenceId)) {
sequenceId = route.queryParams.sequenceId; sequenceId = route.queryParams.sequenceId;
} }
return this.bitstreamDataService.findByItemHandle( return this.bitstreamDataService.findByItemHandle(
`${prefix}/${suffix}`, `${prefix}/${suffix}`,
sequenceId, sequenceId,
filename, filename,
).pipe( ).pipe(
getFirstCompletedRemoteData() getFirstCompletedRemoteData()
); );
} }
} }

View File

@@ -61,11 +61,11 @@ describe('BrowseByDatePageComponent', () => {
} }
}); });
const mockBrowseService = { const mockBrowseService = {
getBrowseEntriesFor: (options: BrowseEntrySearchOptions) => toRemoteData([]), getBrowseEntriesFor: (options: BrowseEntrySearchOptions) => toRemoteData([]),
getBrowseItemsFor: (value: string, options: BrowseEntrySearchOptions) => toRemoteData([firstItem]), getBrowseItemsFor: (value: string, options: BrowseEntrySearchOptions) => toRemoteData([firstItem]),
getFirstItemFor: (definition: string, scope?: string, sortDirection?: SortDirection) => null getFirstItemFor: (definition: string, scope?: string, sortDirection?: SortDirection) => null
}; };
const mockDsoService = { const mockDsoService = {
findById: () => createSuccessfulRemoteDataObject$(mockCommunity) findById: () => createSuccessfulRemoteDataObject$(mockCommunity)

View File

@@ -110,7 +110,7 @@ export class BrowseByMetadataPageComponent implements OnInit, OnDestroy {
/** /**
* The authority key (may be undefined) associated with {@link #value}. * The authority key (may be undefined) associated with {@link #value}.
*/ */
authority: string; authority: string;
/** /**
* The current startsWith option (fetched and updated from query-params) * The current startsWith option (fetched and updated from query-params)
@@ -133,11 +133,11 @@ export class BrowseByMetadataPageComponent implements OnInit, OnDestroy {
this.fetchThumbnails = this.appConfig.browseBy.showThumbnails; this.fetchThumbnails = this.appConfig.browseBy.showThumbnails;
this.paginationConfig = Object.assign(new PaginationComponentOptions(), { this.paginationConfig = Object.assign(new PaginationComponentOptions(), {
id: BBM_PAGINATION_ID, id: BBM_PAGINATION_ID,
currentPage: 1, currentPage: 1,
pageSize: this.appConfig.browseBy.pageSize, pageSize: this.appConfig.browseBy.pageSize,
}); });
} }
ngOnInit(): void { ngOnInit(): void {
@@ -152,28 +152,28 @@ export class BrowseByMetadataPageComponent implements OnInit, OnDestroy {
return [Object.assign({}, routeParams, queryParams),currentPage,currentSort]; return [Object.assign({}, routeParams, queryParams),currentPage,currentSort];
}) })
).subscribe(([params, currentPage, currentSort]: [Params, PaginationComponentOptions, SortOptions]) => { ).subscribe(([params, currentPage, currentSort]: [Params, PaginationComponentOptions, SortOptions]) => {
this.browseId = params.id || this.defaultBrowseId; this.browseId = params.id || this.defaultBrowseId;
this.authority = params.authority; this.authority = params.authority;
if (typeof params.value === 'string'){ if (typeof params.value === 'string'){
this.value = params.value.trim(); this.value = params.value.trim();
} else { } else {
this.value = ''; this.value = '';
} }
if (typeof params.startsWith === 'string'){ if (typeof params.startsWith === 'string'){
this.startsWith = params.startsWith.trim(); this.startsWith = params.startsWith.trim();
} }
if (isNotEmpty(this.value)) { if (isNotEmpty(this.value)) {
this.updatePageWithItems( this.updatePageWithItems(
browseParamsToOptions(params, currentPage, currentSort, this.browseId, this.fetchThumbnails), this.value, this.authority); browseParamsToOptions(params, currentPage, currentSort, this.browseId, this.fetchThumbnails), this.value, this.authority);
} else { } else {
this.updatePage(browseParamsToOptions(params, currentPage, currentSort, this.browseId, false)); this.updatePage(browseParamsToOptions(params, currentPage, currentSort, this.browseId, false));
} }
this.updateParent(params.scope); this.updateParent(params.scope);
this.updateLogo(); this.updateLogo();
})); }));
this.updateStartsWithTextOptions(); this.updateStartsWithTextOptions();
} }
@@ -290,9 +290,9 @@ export class BrowseByMetadataPageComponent implements OnInit, OnDestroy {
* @returns BrowseEntrySearchOptions instance * @returns BrowseEntrySearchOptions instance
*/ */
export function getBrowseSearchOptions(defaultBrowseId: string, export function getBrowseSearchOptions(defaultBrowseId: string,
paginationConfig: PaginationComponentOptions, paginationConfig: PaginationComponentOptions,
sortConfig: SortOptions, sortConfig: SortOptions,
fetchThumbnails?: boolean) { fetchThumbnails?: boolean) {
if (!hasValue(fetchThumbnails)) { if (!hasValue(fetchThumbnails)) {
fetchThumbnails = false; fetchThumbnails = false;
} }
@@ -309,10 +309,10 @@ export function getBrowseSearchOptions(defaultBrowseId: string,
* @param fetchThumbnail Optional parameter for requesting thumbnail images * @param fetchThumbnail Optional parameter for requesting thumbnail images
*/ */
export function browseParamsToOptions(params: any, export function browseParamsToOptions(params: any,
paginationConfig: PaginationComponentOptions, paginationConfig: PaginationComponentOptions,
sortConfig: SortOptions, sortConfig: SortOptions,
metadata?: string, metadata?: string,
fetchThumbnail?: boolean): BrowseEntrySearchOptions { fetchThumbnail?: boolean): BrowseEntrySearchOptions {
return new BrowseEntrySearchOptions( return new BrowseEntrySearchOptions(
metadata, metadata,
paginationConfig, paginationConfig,

View File

@@ -36,7 +36,7 @@ describe('BrowseByTaxonomyPageComponent', () => {
], ],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}) })
.compileComponents(); .compileComponents();
}); });
beforeEach(() => { beforeEach(() => {

View File

@@ -86,9 +86,9 @@ export class BrowseByTaxonomyPageComponent implements OnInit, OnDestroy {
* @param detail VocabularyEntryDetail to be added * @param detail VocabularyEntryDetail to be added
*/ */
onSelect(detail: VocabularyEntryDetail): void { onSelect(detail: VocabularyEntryDetail): void {
this.selectedItems.push(detail); this.selectedItems.push(detail);
this.filterValues = this.selectedItems this.filterValues = this.selectedItems
.map((item: VocabularyEntryDetail) => `${item.value},equals`); .map((item: VocabularyEntryDetail) => `${item.value},equals`);
this.updateQueryParams(); this.updateQueryParams();
} }

View File

@@ -98,9 +98,9 @@ export class CollectionFormComponent extends ComColFormComponent<Collection> imp
// retrieve all entity types to populate the dropdowns selection // retrieve all entity types to populate the dropdowns selection
entities$.subscribe((entityTypes: ItemType[]) => { entities$.subscribe((entityTypes: ItemType[]) => {
entityTypes entityTypes
.filter((type: ItemType) => type.label !== NONE_ENTITY_TYPE) .filter((type: ItemType) => type.label !== NONE_ENTITY_TYPE)
.forEach((type: ItemType, index: number) => { .forEach((type: ItemType, index: number) => {
this.entityTypeSelection.add({ this.entityTypeSelection.add({
disabled: false, disabled: false,
label: type.label, label: type.label,
@@ -112,10 +112,10 @@ export class CollectionFormComponent extends ComColFormComponent<Collection> imp
} }
}); });
this.formModel = [...collectionFormModels, this.entityTypeSelection]; this.formModel = [...collectionFormModels, this.entityTypeSelection];
super.ngOnInit(); super.ngOnInit();
this.chd.detectChanges(); this.chd.detectChanges();
}); });
} }

View File

@@ -176,16 +176,16 @@ export class CollectionItemMapperComponent implements OnInit {
map((collectionRD: RemoteData<Collection>) => collectionRD.payload), map((collectionRD: RemoteData<Collection>) => collectionRD.payload),
switchMap((collection: Collection) => switchMap((collection: Collection) =>
observableCombineLatest(ids.map((id: string) => { observableCombineLatest(ids.map((id: string) => {
if (remove) { if (remove) {
return this.itemDataService.removeMappingFromCollection(id, collection.id).pipe( return this.itemDataService.removeMappingFromCollection(id, collection.id).pipe(
getFirstCompletedRemoteData() getFirstCompletedRemoteData()
); );
} else { } else {
return this.itemDataService.mapToCollection(id, collection._links.self.href).pipe( return this.itemDataService.mapToCollection(id, collection._links.self.href).pipe(
getFirstCompletedRemoteData() getFirstCompletedRemoteData()
); );
}
} }
}
)) ))
) )
); );

View File

@@ -38,6 +38,6 @@ export class CreateCollectionPageGuard implements CanActivate {
this.router.navigate(['/404']); this.router.navigate(['/404']);
} }
}) })
); );
} }
} }

View File

@@ -10,7 +10,7 @@ xdescribe('CollectionAccessControlComponent', () => {
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
declarations: [ CollectionAccessControlComponent ] declarations: [ CollectionAccessControlComponent ]
}) })
.compileComponents(); .compileComponents();
}); });
beforeEach(() => { beforeEach(() => {

View File

@@ -101,29 +101,29 @@ export class CollectionSourceControlsComponent implements OnDestroy {
map((rd) => rd.payload), map((rd) => rd.payload),
hasValueOperator(), hasValueOperator(),
).subscribe((process: Process) => { ).subscribe((process: Process) => {
if (process.processStatus.toString() !== ProcessStatus[ProcessStatus.COMPLETED].toString() && if (process.processStatus.toString() !== ProcessStatus[ProcessStatus.COMPLETED].toString() &&
process.processStatus.toString() !== ProcessStatus[ProcessStatus.FAILED].toString()) { process.processStatus.toString() !== ProcessStatus[ProcessStatus.FAILED].toString()) {
// Ping the current process state every 5s // Ping the current process state every 5s
setTimeout(() => { setTimeout(() => {
this.requestService.setStaleByHrefSubstring(process._links.self.href); this.requestService.setStaleByHrefSubstring(process._links.self.href);
}, 5000); }, 5000);
}
if (process.processStatus.toString() === ProcessStatus[ProcessStatus.FAILED].toString()) {
this.notificationsService.error(this.translateService.get('collection.source.controls.test.failed'));
this.testConfigRunning$.next(false);
}
if (process.processStatus.toString() === ProcessStatus[ProcessStatus.COMPLETED].toString()) {
this.bitstreamService.findByHref(process._links.output.href).pipe(getFirstSucceededRemoteDataPayload()).subscribe((bitstream) => {
this.httpClient.get(bitstream._links.content.href, {responseType: 'text'}).subscribe((data: any) => {
const output = data.replaceAll(new RegExp('.*\\@(.*)', 'g'), '$1')
.replaceAll('The script has started', '')
.replaceAll('The script has completed', '');
this.notificationsService.info(this.translateService.get('collection.source.controls.test.completed'), output);
});
});
this.testConfigRunning$.next(false);
}
} }
if (process.processStatus.toString() === ProcessStatus[ProcessStatus.FAILED].toString()) {
this.notificationsService.error(this.translateService.get('collection.source.controls.test.failed'));
this.testConfigRunning$.next(false);
}
if (process.processStatus.toString() === ProcessStatus[ProcessStatus.COMPLETED].toString()) {
this.bitstreamService.findByHref(process._links.output.href).pipe(getFirstSucceededRemoteDataPayload()).subscribe((bitstream) => {
this.httpClient.get(bitstream._links.content.href, {responseType: 'text'}).subscribe((data: any) => {
const output = data.replaceAll(new RegExp('.*\\@(.*)', 'g'), '$1')
.replaceAll('The script has started', '')
.replaceAll('The script has completed', '');
this.notificationsService.info(this.translateService.get('collection.source.controls.test.completed'), output);
});
});
this.testConfigRunning$.next(false);
}
}
)); ));
} }
@@ -153,24 +153,24 @@ export class CollectionSourceControlsComponent implements OnDestroy {
map((rd) => rd.payload), map((rd) => rd.payload),
hasValueOperator(), hasValueOperator(),
).subscribe((process) => { ).subscribe((process) => {
if (process.processStatus.toString() !== ProcessStatus[ProcessStatus.COMPLETED].toString() && if (process.processStatus.toString() !== ProcessStatus[ProcessStatus.COMPLETED].toString() &&
process.processStatus.toString() !== ProcessStatus[ProcessStatus.FAILED].toString()) { process.processStatus.toString() !== ProcessStatus[ProcessStatus.FAILED].toString()) {
// Ping the current process state every 5s // Ping the current process state every 5s
setTimeout(() => { setTimeout(() => {
this.requestService.setStaleByHrefSubstring(process._links.self.href); this.requestService.setStaleByHrefSubstring(process._links.self.href);
this.requestService.setStaleByHrefSubstring(this.collection._links.self.href);
}, 5000);
}
if (process.processStatus.toString() === ProcessStatus[ProcessStatus.FAILED].toString()) {
this.notificationsService.error(this.translateService.get('collection.source.controls.import.failed'));
this.importRunning$.next(false);
}
if (process.processStatus.toString() === ProcessStatus[ProcessStatus.COMPLETED].toString()) {
this.notificationsService.success(this.translateService.get('collection.source.controls.import.completed'));
this.requestService.setStaleByHrefSubstring(this.collection._links.self.href); this.requestService.setStaleByHrefSubstring(this.collection._links.self.href);
this.importRunning$.next(false); }, 5000);
}
} }
if (process.processStatus.toString() === ProcessStatus[ProcessStatus.FAILED].toString()) {
this.notificationsService.error(this.translateService.get('collection.source.controls.import.failed'));
this.importRunning$.next(false);
}
if (process.processStatus.toString() === ProcessStatus[ProcessStatus.COMPLETED].toString()) {
this.notificationsService.success(this.translateService.get('collection.source.controls.import.completed'));
this.requestService.setStaleByHrefSubstring(this.collection._links.self.href);
this.importRunning$.next(false);
}
}
)); ));
} }
@@ -200,24 +200,24 @@ export class CollectionSourceControlsComponent implements OnDestroy {
map((rd) => rd.payload), map((rd) => rd.payload),
hasValueOperator(), hasValueOperator(),
).subscribe((process) => { ).subscribe((process) => {
if (process.processStatus.toString() !== ProcessStatus[ProcessStatus.COMPLETED].toString() && if (process.processStatus.toString() !== ProcessStatus[ProcessStatus.COMPLETED].toString() &&
process.processStatus.toString() !== ProcessStatus[ProcessStatus.FAILED].toString()) { process.processStatus.toString() !== ProcessStatus[ProcessStatus.FAILED].toString()) {
// Ping the current process state every 5s // Ping the current process state every 5s
setTimeout(() => { setTimeout(() => {
this.requestService.setStaleByHrefSubstring(process._links.self.href); this.requestService.setStaleByHrefSubstring(process._links.self.href);
this.requestService.setStaleByHrefSubstring(this.collection._links.self.href);
}, 5000);
}
if (process.processStatus.toString() === ProcessStatus[ProcessStatus.FAILED].toString()) {
this.notificationsService.error(this.translateService.get('collection.source.controls.reset.failed'));
this.reImportRunning$.next(false);
}
if (process.processStatus.toString() === ProcessStatus[ProcessStatus.COMPLETED].toString()) {
this.notificationsService.success(this.translateService.get('collection.source.controls.reset.completed'));
this.requestService.setStaleByHrefSubstring(this.collection._links.self.href); this.requestService.setStaleByHrefSubstring(this.collection._links.self.href);
this.reImportRunning$.next(false); }, 5000);
}
} }
if (process.processStatus.toString() === ProcessStatus[ProcessStatus.FAILED].toString()) {
this.notificationsService.error(this.translateService.get('collection.source.controls.reset.failed'));
this.reImportRunning$.next(false);
}
if (process.processStatus.toString() === ProcessStatus[ProcessStatus.COMPLETED].toString()) {
this.notificationsService.success(this.translateService.get('collection.source.controls.reset.completed'));
this.requestService.setStaleByHrefSubstring(this.collection._links.self.href);
this.reImportRunning$.next(false);
}
}
)); ));
} }

View File

@@ -64,7 +64,7 @@ import { CollectionAccessControlComponent } from './collection-access-control/co
component: CollectionAccessControlComponent, component: CollectionAccessControlComponent,
data: { title: 'collection.edit.tabs.access-control.title', showBreadcrumbs: true } data: { title: 'collection.edit.tabs.access-control.title', showBreadcrumbs: true }
}, },
/* { /* {
path: 'authorizations', path: 'authorizations',
component: CollectionAuthorizationsComponent, component: CollectionAuthorizationsComponent,
data: { title: 'collection.edit.tabs.authorizations.title', showBreadcrumbs: true } data: { title: 'collection.edit.tabs.authorizations.title', showBreadcrumbs: true }

View File

@@ -38,10 +38,10 @@ describe('CommunityListService', () => {
id: 'ce64f48e-2c9b-411a-ac36-ee429c0e6a88', id: 'ce64f48e-2c9b-411a-ac36-ee429c0e6a88',
uuid: 'ce64f48e-2c9b-411a-ac36-ee429c0e6a88', uuid: 'ce64f48e-2c9b-411a-ac36-ee429c0e6a88',
}), }),
Object.assign(new Community(), { Object.assign(new Community(), {
id: '59ee713b-ee53-4220-8c3f-9860dc84fe33', id: '59ee713b-ee53-4220-8c3f-9860dc84fe33',
uuid: '59ee713b-ee53-4220-8c3f-9860dc84fe33', uuid: '59ee713b-ee53-4220-8c3f-9860dc84fe33',
}) })
]; ];
mockCollectionsPage1 = [ mockCollectionsPage1 = [
Object.assign(new Collection(), { Object.assign(new Collection(), {

View File

@@ -150,15 +150,15 @@ export class CommunityListService {
*/ */
private getTopCommunities(options: FindListOptions): Observable<PaginatedList<Community>> { private getTopCommunities(options: FindListOptions): Observable<PaginatedList<Community>> {
return this.communityDataService.findTop({ return this.communityDataService.findTop({
currentPage: options.currentPage, currentPage: options.currentPage,
elementsPerPage: this.pageSize, elementsPerPage: this.pageSize,
sort: { sort: {
field: options.sort.field, field: options.sort.field,
direction: options.sort.direction direction: options.sort.direction
} }
}, },
followLink('subcommunities', { findListOptions: this.configOnePage }), followLink('subcommunities', { findListOptions: this.configOnePage }),
followLink('collections', { findListOptions: this.configOnePage })) followLink('collections', { findListOptions: this.configOnePage }))
.pipe( .pipe(
getFirstSucceededRemoteData(), getFirstSucceededRemoteData(),
map((results) => results.payload), map((results) => results.payload),
@@ -173,9 +173,9 @@ export class CommunityListService {
* @param expandedNodes List of expanded nodes; if a node is not expanded its subcommunities and collections need not be added to the list * @param expandedNodes List of expanded nodes; if a node is not expanded its subcommunities and collections need not be added to the list
*/ */
public transformListOfCommunities(listOfPaginatedCommunities: PaginatedList<Community>, public transformListOfCommunities(listOfPaginatedCommunities: PaginatedList<Community>,
level: number, level: number,
parent: FlatNode, parent: FlatNode,
expandedNodes: FlatNode[]): Observable<FlatNode[]> { expandedNodes: FlatNode[]): Observable<FlatNode[]> {
if (isNotEmpty(listOfPaginatedCommunities.page)) { if (isNotEmpty(listOfPaginatedCommunities.page)) {
let currentPage = listOfPaginatedCommunities.currentPage; let currentPage = listOfPaginatedCommunities.currentPage;
if (isNotEmpty(parent)) { if (isNotEmpty(parent)) {
@@ -222,11 +222,11 @@ export class CommunityListService {
let subcoms = []; let subcoms = [];
for (let i = 1; i <= currentCommunityPage; i++) { for (let i = 1; i <= currentCommunityPage; i++) {
const nextSetOfSubcommunitiesPage = this.communityDataService.findByParent(community.uuid, { const nextSetOfSubcommunitiesPage = this.communityDataService.findByParent(community.uuid, {
elementsPerPage: this.pageSize, elementsPerPage: this.pageSize,
currentPage: i currentPage: i
}, },
followLink('subcommunities', { findListOptions: this.configOnePage }), followLink('subcommunities', { findListOptions: this.configOnePage }),
followLink('collections', { findListOptions: this.configOnePage })) followLink('collections', { findListOptions: this.configOnePage }))
.pipe( .pipe(
getFirstCompletedRemoteData(), getFirstCompletedRemoteData(),
switchMap((rd: RemoteData<PaginatedList<Community>>) => { switchMap((rd: RemoteData<PaginatedList<Community>>) => {

View File

@@ -27,11 +27,11 @@ describe('CommunityListComponent', () => {
uuid: 'ce64f48e-2c9b-411a-ac36-ee429c0e6a88', uuid: 'ce64f48e-2c9b-411a-ac36-ee429c0e6a88',
name: 'subcommunity1', name: 'subcommunity1',
}), }),
Object.assign(new Community(), { Object.assign(new Community(), {
id: '59ee713b-ee53-4220-8c3f-9860dc84fe33', id: '59ee713b-ee53-4220-8c3f-9860dc84fe33',
uuid: '59ee713b-ee53-4220-8c3f-9860dc84fe33', uuid: '59ee713b-ee53-4220-8c3f-9860dc84fe33',
name: 'subcommunity2', name: 'subcommunity2',
}) })
]; ];
const mockCollectionsPage1 = [ const mockCollectionsPage1 = [
Object.assign(new Collection(), { Object.assign(new Collection(), {

View File

@@ -85,7 +85,7 @@ export class CommunityFormComponent extends ComColFormComponent<Community> imple
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
const dsoChange: SimpleChange = changes.dso; const dsoChange: SimpleChange = changes.dso;
if (this.dso && dsoChange && !dsoChange.isFirstChange()) { if (this.dso && dsoChange && !dsoChange.isFirstChange()) {
super.ngOnInit(); super.ngOnInit();
} }
} }
} }

View File

@@ -38,7 +38,7 @@ export class CreateCommunityPageGuard implements CanActivate {
this.router.navigate(['/404']); this.router.navigate(['/404']);
} }
} }
) )
); );
} }
} }

View File

@@ -10,7 +10,7 @@ xdescribe('CommunityAccessControlComponent', () => {
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
declarations: [ CommunityAccessControlComponent ] declarations: [ CommunityAccessControlComponent ]
}) })
.compileComponents(); .compileComponents();
}); });
beforeEach(() => { beforeEach(() => {

View File

@@ -45,54 +45,54 @@ describe('CommunityPageSubCollectionList Component', () => {
] ]
} }
}), }),
Object.assign(new Community(), { Object.assign(new Community(), {
id: '123456789-2', id: '123456789-2',
metadata: { metadata: {
'dc.title': [ 'dc.title': [
{ language: 'en_US', value: 'Collection 2' } { language: 'en_US', value: 'Collection 2' }
] ]
} }
}), }),
Object.assign(new Community(), { Object.assign(new Community(), {
id: '123456789-3', id: '123456789-3',
metadata: { metadata: {
'dc.title': [ 'dc.title': [
{ language: 'en_US', value: 'Collection 3' } { language: 'en_US', value: 'Collection 3' }
] ]
} }
}), }),
Object.assign(new Community(), { Object.assign(new Community(), {
id: '123456789-4', id: '123456789-4',
metadata: { metadata: {
'dc.title': [ 'dc.title': [
{ language: 'en_US', value: 'Collection 4' } { language: 'en_US', value: 'Collection 4' }
] ]
} }
}), }),
Object.assign(new Community(), { Object.assign(new Community(), {
id: '123456789-5', id: '123456789-5',
metadata: { metadata: {
'dc.title': [ 'dc.title': [
{ language: 'en_US', value: 'Collection 5' } { language: 'en_US', value: 'Collection 5' }
] ]
} }
}), }),
Object.assign(new Community(), { Object.assign(new Community(), {
id: '123456789-6', id: '123456789-6',
metadata: { metadata: {
'dc.title': [ 'dc.title': [
{ language: 'en_US', value: 'Collection 6' } { language: 'en_US', value: 'Collection 6' }
] ]
} }
}), }),
Object.assign(new Community(), { Object.assign(new Community(), {
id: '123456789-7', id: '123456789-7',
metadata: { metadata: {
'dc.title': [ 'dc.title': [
{ language: 'en_US', value: 'Collection 7' } { language: 'en_US', value: 'Collection 7' }
] ]
} }
}) })
]; ];
const mockCommunity = Object.assign(new Community(), { const mockCommunity = Object.assign(new Community(), {

View File

@@ -74,8 +74,8 @@ export class CommunityPageSubCollectionListComponent implements OnInit, OnDestro
* Initialise the list of collections * Initialise the list of collections
*/ */
initPage() { initPage() {
const pagination$ = this.paginationService.getCurrentPagination(this.config.id, this.config); const pagination$ = this.paginationService.getCurrentPagination(this.config.id, this.config);
const sort$ = this.paginationService.getCurrentSort(this.config.id, this.sortConfig); const sort$ = this.paginationService.getCurrentSort(this.config.id, this.sortConfig);
observableCombineLatest([pagination$, sort$]).pipe( observableCombineLatest([pagination$, sort$]).pipe(
switchMap(([currentPagination, currentSort]) => { switchMap(([currentPagination, currentSort]) => {

View File

@@ -45,54 +45,54 @@ describe('CommunityPageSubCommunityListComponent Component', () => {
] ]
} }
}), }),
Object.assign(new Community(), { Object.assign(new Community(), {
id: '123456789-2', id: '123456789-2',
metadata: { metadata: {
'dc.title': [ 'dc.title': [
{ language: 'en_US', value: 'SubCommunity 2' } { language: 'en_US', value: 'SubCommunity 2' }
] ]
} }
}), }),
Object.assign(new Community(), { Object.assign(new Community(), {
id: '123456789-3', id: '123456789-3',
metadata: { metadata: {
'dc.title': [ 'dc.title': [
{ language: 'en_US', value: 'SubCommunity 3' } { language: 'en_US', value: 'SubCommunity 3' }
] ]
} }
}), }),
Object.assign(new Community(), { Object.assign(new Community(), {
id: '12345678942', id: '12345678942',
metadata: { metadata: {
'dc.title': [ 'dc.title': [
{ language: 'en_US', value: 'SubCommunity 4' } { language: 'en_US', value: 'SubCommunity 4' }
] ]
} }
}), }),
Object.assign(new Community(), { Object.assign(new Community(), {
id: '123456789-5', id: '123456789-5',
metadata: { metadata: {
'dc.title': [ 'dc.title': [
{ language: 'en_US', value: 'SubCommunity 5' } { language: 'en_US', value: 'SubCommunity 5' }
] ]
} }
}), }),
Object.assign(new Community(), { Object.assign(new Community(), {
id: '123456789-6', id: '123456789-6',
metadata: { metadata: {
'dc.title': [ 'dc.title': [
{ language: 'en_US', value: 'SubCommunity 6' } { language: 'en_US', value: 'SubCommunity 6' }
] ]
} }
}), }),
Object.assign(new Community(), { Object.assign(new Community(), {
id: '123456789-7', id: '123456789-7',
metadata: { metadata: {
'dc.title': [ 'dc.title': [
{ language: 'en_US', value: 'SubCommunity 7' } { language: 'en_US', value: 'SubCommunity 7' }
] ]
} }
}) })
]; ];
const mockCommunity = Object.assign(new Community(), { const mockCommunity = Object.assign(new Community(), {

View File

@@ -24,7 +24,7 @@ export abstract class AuthRequestService {
constructor(protected halService: HALEndpointService, constructor(protected halService: HALEndpointService,
protected requestService: RequestService, protected requestService: RequestService,
private rdbService: RemoteDataBuildService private rdbService: RemoteDataBuildService
) { ) {
} }
/** /**

View File

@@ -58,7 +58,7 @@ import { AuthorizationDataService } from '../data/feature-authorization/authoriz
// Action Types that do not break/prevent the user from an idle state // Action Types that do not break/prevent the user from an idle state
const IDLE_TIMER_IGNORE_TYPES: string[] const IDLE_TIMER_IGNORE_TYPES: string[]
= [...Object.values(AuthActionTypes).filter((t: string) => t !== AuthActionTypes.UNSET_USER_AS_IDLE), = [...Object.values(AuthActionTypes).filter((t: string) => t !== AuthActionTypes.UNSET_USER_AS_IDLE),
...Object.values(RequestActionTypes), ...Object.values(NotificationsActionTypes)]; ...Object.values(RequestActionTypes), ...Object.values(NotificationsActionTypes)];
@Injectable() @Injectable()
export class AuthEffects { export class AuthEffects {
@@ -213,7 +213,7 @@ export class AuthEffects {
* authorizations endpoint, to be sure to have consistent responses after a login with external idp * authorizations endpoint, to be sure to have consistent responses after a login with external idp
* *
*/ */
invalidateAuthorizationsRequestCache$ = createEffect(() => this.actions$ invalidateAuthorizationsRequestCache$ = createEffect(() => this.actions$
.pipe(ofType(StoreActionTypes.REHYDRATE), .pipe(ofType(StoreActionTypes.REHYDRATE),
tap(() => this.authorizationsService.invalidateAuthorizationsRequestCache()) tap(() => this.authorizationsService.invalidateAuthorizationsRequestCache())
), { dispatch: false }); ), { dispatch: false });

View File

@@ -208,7 +208,7 @@ export class AuthInterceptor implements HttpInterceptor {
status: 500, status: 500,
timestamp: Date.now(), timestamp: Date.now(),
path: '' path: ''
}; };
} }
} else { } else {
authStatus.error = error; authStatus.error = error;

View File

@@ -28,14 +28,14 @@ export class AuthStatus implements CacheableObject {
* The unique identifier of this auth status * The unique identifier of this auth status
*/ */
@autoserialize @autoserialize
id: string; id: string;
/** /**
* The type for this AuthStatus * The type for this AuthStatus
*/ */
@excludeFromEquals @excludeFromEquals
@autoserialize @autoserialize
type: ResourceType; type: ResourceType;
/** /**
* The UUID of this auth status * The UUID of this auth status
@@ -43,25 +43,25 @@ export class AuthStatus implements CacheableObject {
* It is based on the ID, so it will be the same for each refresh. * It is based on the ID, so it will be the same for each refresh.
*/ */
@deserializeAs(new IDToUUIDSerializer('auth-status'), 'id') @deserializeAs(new IDToUUIDSerializer('auth-status'), 'id')
uuid: string; uuid: string;
/** /**
* True if REST API is up and running, should never return false * True if REST API is up and running, should never return false
*/ */
@autoserialize @autoserialize
okay: boolean; okay: boolean;
/** /**
* If the auth status represents an authenticated state * If the auth status represents an authenticated state
*/ */
@autoserialize @autoserialize
authenticated: boolean; authenticated: boolean;
/** /**
* The {@link HALLink}s for this AuthStatus * The {@link HALLink}s for this AuthStatus
*/ */
@deserialize @deserialize
_links: { _links: {
self: HALLink; self: HALLink;
eperson: HALLink; eperson: HALLink;
specialGroups: HALLink; specialGroups: HALLink;
@@ -72,32 +72,32 @@ export class AuthStatus implements CacheableObject {
* Will be undefined unless the eperson {@link HALLink} has been resolved. * Will be undefined unless the eperson {@link HALLink} has been resolved.
*/ */
@link(EPERSON) @link(EPERSON)
eperson?: Observable<RemoteData<EPerson>>; eperson?: Observable<RemoteData<EPerson>>;
/** /**
* The SpecialGroup of this auth status * The SpecialGroup of this auth status
* Will be undefined unless the SpecialGroup {@link HALLink} has been resolved. * Will be undefined unless the SpecialGroup {@link HALLink} has been resolved.
*/ */
@link(GROUP, true) @link(GROUP, true)
specialGroups?: Observable<RemoteData<PaginatedList<Group>>>; specialGroups?: Observable<RemoteData<PaginatedList<Group>>>;
/** /**
* True if the token is valid, false if there was no token or the token wasn't valid * True if the token is valid, false if there was no token or the token wasn't valid
*/ */
@autoserialize @autoserialize
token?: AuthTokenInfo; token?: AuthTokenInfo;
/** /**
* Authentication error if there was one for this status * Authentication error if there was one for this status
*/ */
// TODO should be refactored to use the RemoteData error // TODO should be refactored to use the RemoteData error
@autoserialize @autoserialize
error?: AuthError; error?: AuthError;
/** /**
* All authentication methods enabled at the backend * All authentication methods enabled at the backend
*/ */
@autoserialize @autoserialize
authMethods: AuthMethod[]; authMethods: AuthMethod[];
} }

View File

@@ -17,19 +17,19 @@ export class ShortLivedToken implements CacheableObject {
*/ */
@excludeFromEquals @excludeFromEquals
@autoserialize @autoserialize
type: ResourceType; type: ResourceType;
/** /**
* The value for this ShortLivedToken * The value for this ShortLivedToken
*/ */
@autoserializeAs('token') @autoserializeAs('token')
value: string; value: string;
/** /**
* The {@link HALLink}s for this ShortLivedToken * The {@link HALLink}s for this ShortLivedToken
*/ */
@deserialize @deserialize
_links: { _links: {
self: HALLink; self: HALLink;
}; };
} }

View File

@@ -45,11 +45,11 @@ export class ServerAuthRequestService extends AuthRequestService {
map((response: HttpResponse<any>) => response.headers.get(XSRF_RESPONSE_HEADER)), map((response: HttpResponse<any>) => response.headers.get(XSRF_RESPONSE_HEADER)),
// Use that token to create an HttpHeaders object // Use that token to create an HttpHeaders object
map((xsrfToken: string) => new HttpHeaders() map((xsrfToken: string) => new HttpHeaders()
.set('Content-Type', 'application/json; charset=utf-8') .set('Content-Type', 'application/json; charset=utf-8')
// set the token as the XSRF header // set the token as the XSRF header
.set(XSRF_REQUEST_HEADER, xsrfToken) .set(XSRF_REQUEST_HEADER, xsrfToken)
// and as the DSPACE-XSRF-COOKIE // and as the DSPACE-XSRF-COOKIE
.set('Cookie', `${DSPACE_XSRF_COOKIE}=${xsrfToken}`)), .set('Cookie', `${DSPACE_XSRF_COOKIE}=${xsrfToken}`)),
map((headers: HttpHeaders) => map((headers: HttpHeaders) =>
// Create a new PostRequest using those headers and the given href // Create a new PostRequest using those headers and the given href
new PostRequest( new PostRequest(

View File

@@ -25,9 +25,9 @@ import { BrowseDefinition } from '../shared/browse-definition.model';
* Use a GET request specific for BrowseDefinitions. * Use a GET request specific for BrowseDefinitions.
*/ */
export const createAndSendBrowseDefinitionGetRequest = (requestService: RequestService, export const createAndSendBrowseDefinitionGetRequest = (requestService: RequestService,
responseMsToLive: number, responseMsToLive: number,
href$: string | Observable<string>, href$: string | Observable<string>,
useCachedVersionIfAvailable: boolean = true): void => { useCachedVersionIfAvailable: boolean = true): void => {
if (isNotEmpty(href$)) { if (isNotEmpty(href$)) {
if (typeof href$ === 'string') { if (typeof href$ === 'string') {
href$ = observableOf(href$); href$ = observableOf(href$);

View File

@@ -65,7 +65,7 @@ export const link = <T extends HALResource>(
resourceType: ResourceType, resourceType: ResourceType,
isList = false, isList = false,
linkName?: keyof T['_links'], linkName?: keyof T['_links'],
) => { ) => {
return (target: T, propertyName: string) => { return (target: T, propertyName: string) => {
let targetMap = linkMap.get(target.constructor); let targetMap = linkMap.get(target.constructor);

View File

@@ -3,9 +3,9 @@ import { autoserialize } from 'cerialize';
export class SelfLink { export class SelfLink {
@autoserialize @autoserialize
self: string; self: string;
@autoserialize @autoserialize
uuid: string; uuid: string;
} }

View File

@@ -16,7 +16,7 @@ export class ObjectCacheEffects {
* This assumes that the server cached everything a negligible * This assumes that the server cached everything a negligible
* time ago, and will likely need to be revisited later * time ago, and will likely need to be revisited later
*/ */
fixTimestampsOnRehydrate = createEffect(() => this.actions$ fixTimestampsOnRehydrate = createEffect(() => this.actions$
.pipe(ofType(StoreActionTypes.REHYDRATE), .pipe(ofType(StoreActionTypes.REHYDRATE),
map(() => new ResetObjectCacheTimestampsAction(new Date().getTime())) map(() => new ResetObjectCacheTimestampsAction(new Date().getTime()))
)); ));

View File

@@ -82,12 +82,12 @@ export class ObjectCacheService {
const cacheEntry$ = this.getByHref(href); const cacheEntry$ = this.getByHref(href);
const altLinks$ = cacheEntry$.pipe(map((entry: ObjectCacheEntry) => entry.alternativeLinks), take(1)); const altLinks$ = cacheEntry$.pipe(map((entry: ObjectCacheEntry) => entry.alternativeLinks), take(1));
const childLinks$ = cacheEntry$.pipe(map((entry: ObjectCacheEntry) => { const childLinks$ = cacheEntry$.pipe(map((entry: ObjectCacheEntry) => {
return Object return Object
.entries(entry.data._links) .entries(entry.data._links)
.filter(([key, value]: [string, HALLink]) => key !== 'self') .filter(([key, value]: [string, HALLink]) => key !== 'self')
.map(([key, value]: [string, HALLink]) => value.href); .map(([key, value]: [string, HALLink]) => value.href);
}), }),
take(1) take(1)
); );
this.removeLinksFromAlternativeLinkIndex(altLinks$); this.removeLinksFromAlternativeLinkIndex(altLinks$);
this.removeLinksFromAlternativeLinkIndex(childLinks$); this.removeLinksFromAlternativeLinkIndex(childLinks$);
@@ -96,8 +96,8 @@ export class ObjectCacheService {
private removeLinksFromAlternativeLinkIndex(links$: Observable<string[]>) { private removeLinksFromAlternativeLinkIndex(links$: Observable<string[]>) {
links$.subscribe((links: string[]) => links.forEach((link: string) => { links$.subscribe((links: string[]) => links.forEach((link: string) => {
this.store.dispatch(new RemoveFromIndexBySubstringAction(IndexName.ALTERNATIVE_OBJECT_LINK, link)); this.store.dispatch(new RemoveFromIndexBySubstringAction(IndexName.ALTERNATIVE_OBJECT_LINK, link));
} }
)); ));
} }
@@ -129,14 +129,14 @@ export class ObjectCacheService {
getObjectByHref<T extends CacheableObject>(href: string): Observable<T> { getObjectByHref<T extends CacheableObject>(href: string): Observable<T> {
return this.getByHref(href).pipe( return this.getByHref(href).pipe(
map((entry: ObjectCacheEntry) => { map((entry: ObjectCacheEntry) => {
if (isNotEmpty(entry.patches)) { if (isNotEmpty(entry.patches)) {
const flatPatch: Operation[] = [].concat(...entry.patches.map((patch) => patch.operations)); const flatPatch: Operation[] = [].concat(...entry.patches.map((patch) => patch.operations));
const patchedData = applyPatch(entry.data, flatPatch, undefined, false).newDocument; const patchedData = applyPatch(entry.data, flatPatch, undefined, false).newDocument;
return Object.assign({}, entry, { data: patchedData }); return Object.assign({}, entry, { data: patchedData });
} else { } else {
return entry; return entry;
}
} }
}
), ),
map((entry: ObjectCacheEntry) => { map((entry: ObjectCacheEntry) => {
const type: GenericConstructor<T> = getClassForType((entry.data as any).type); const type: GenericConstructor<T> = getClassForType((entry.data as any).type);

View File

@@ -32,7 +32,7 @@ export class ServerSyncBufferEffects {
* Then dispatch a CommitSSBAction * Then dispatch a CommitSSBAction
* When the delay is running, no new AddToSSBActions are processed in this effect * When the delay is running, no new AddToSSBActions are processed in this effect
*/ */
setTimeoutForServerSync = createEffect(() => this.actions$ setTimeoutForServerSync = createEffect(() => this.actions$
.pipe( .pipe(
ofType(ServerSyncBufferActionTypes.ADD), ofType(ServerSyncBufferActionTypes.ADD),
exhaustMap((action: AddToSSBAction) => { exhaustMap((action: AddToSSBAction) => {
@@ -50,7 +50,7 @@ export class ServerSyncBufferEffects {
* When the list of actions is not empty, also dispatch an EmptySSBAction * When the list of actions is not empty, also dispatch an EmptySSBAction
* When the list is empty dispatch a NO_ACTION placeholder action * When the list is empty dispatch a NO_ACTION placeholder action
*/ */
commitServerSyncBuffer = createEffect(() => this.actions$ commitServerSyncBuffer = createEffect(() => this.actions$
.pipe( .pipe(
ofType(ServerSyncBufferActionTypes.COMMIT), ofType(ServerSyncBufferActionTypes.COMMIT),
switchMap((action: CommitSSBAction) => { switchMap((action: CommitSSBAction) => {
@@ -78,8 +78,8 @@ export class ServerSyncBufferEffects {
/* Add extra action to array, to make sure the ServerSyncBuffer is emptied afterwards */ /* Add extra action to array, to make sure the ServerSyncBuffer is emptied afterwards */
if (isNotEmpty(actions) && isNotUndefined(actions[0])) { if (isNotEmpty(actions) && isNotUndefined(actions[0])) {
return observableCombineLatest(...actions).pipe( return observableCombineLatest(...actions).pipe(
switchMap((array) => [...array, new EmptySSBAction(action.payload)]) switchMap((array) => [...array, new EmptySSBAction(action.payload)])
); );
} else { } else {
return observableOf(new NoOpAction()); return observableOf(new NoOpAction());
} }

View File

@@ -86,9 +86,9 @@ function addToServerSyncQueue(state: ServerSyncBufferState, action: AddToSSBActi
* the new state, with a new entry added to the buffer * the new state, with a new entry added to the buffer
*/ */
function emptyServerSyncQueue(state: ServerSyncBufferState, action: EmptySSBAction): ServerSyncBufferState { function emptyServerSyncQueue(state: ServerSyncBufferState, action: EmptySSBAction): ServerSyncBufferState {
let newBuffer = []; let newBuffer = [];
if (hasValue(action.payload)) { if (hasValue(action.payload)) {
newBuffer = state.buffer.filter((entry) => entry.method !== action.payload); newBuffer = state.buffer.filter((entry) => entry.method !== action.payload);
} }
return Object.assign({}, state, { buffer: newBuffer }); return Object.assign({}, state, { buffer: newBuffer });
} }

View File

@@ -20,19 +20,19 @@ export class BulkAccessConditionOptions extends ConfigObject {
*/ */
@excludeFromEquals @excludeFromEquals
@autoserialize @autoserialize
type: ResourceType; type: ResourceType;
@autoserializeAs(String, 'name') @autoserializeAs(String, 'name')
uuid: string; uuid: string;
@autoserialize @autoserialize
id: string; id: string;
@autoserialize @autoserialize
itemAccessConditionOptions: AccessesConditionOption[]; itemAccessConditionOptions: AccessesConditionOption[];
@autoserialize @autoserialize
bitstreamAccessConditionOptions: AccessesConditionOption[]; bitstreamAccessConditionOptions: AccessesConditionOption[];
_links: { self: HALLink }; _links: { self: HALLink };
} }

View File

@@ -3,43 +3,43 @@
*/ */
export class AccessesConditionOption { export class AccessesConditionOption {
/** /**
* The name for this Access Condition * The name for this Access Condition
*/ */
name: string; name: string;
/** /**
* The groupName for this Access Condition * The groupName for this Access Condition
*/ */
groupName: string; groupName: string;
/** /**
* A boolean representing if this Access Condition has a start date * A boolean representing if this Access Condition has a start date
*/ */
hasStartDate: boolean; hasStartDate: boolean;
/** /**
* A boolean representing if this Access Condition has an end date * A boolean representing if this Access Condition has an end date
*/ */
hasEndDate: boolean; hasEndDate: boolean;
/** /**
* Maximum value of the start date * Maximum value of the start date
*/ */
endDateLimit?: string; endDateLimit?: string;
/** /**
* Maximum value of the end date * Maximum value of the end date
*/ */
startDateLimit?: string; startDateLimit?: string;
/** /**
* Maximum value of the start date * Maximum value of the start date
*/ */
maxStartDate?: string; maxStartDate?: string;
/** /**
* Maximum value of the end date * Maximum value of the end date
*/ */
maxEndDate?: string; maxEndDate?: string;
} }

View File

@@ -17,25 +17,25 @@ export class SubmissionAccessModel extends ConfigObject {
* A list of available item access conditions * A list of available item access conditions
*/ */
@autoserialize @autoserialize
accessConditionOptions: AccessesConditionOption[]; accessConditionOptions: AccessesConditionOption[];
/** /**
* Boolean that indicates whether the current item must be findable via search or browse. * Boolean that indicates whether the current item must be findable via search or browse.
*/ */
@autoserialize @autoserialize
discoverable: boolean; discoverable: boolean;
/** /**
* Boolean that indicates whether or not the user can change the discoverable flag. * Boolean that indicates whether or not the user can change the discoverable flag.
*/ */
@autoserialize @autoserialize
canChangeDiscoverable: boolean; canChangeDiscoverable: boolean;
/** /**
* The links to all related resources returned by the rest api. * The links to all related resources returned by the rest api.
*/ */
@deserialize @deserialize
_links: { _links: {
self: HALLink self: HALLink
}; };

View File

@@ -18,20 +18,20 @@ export class SubmissionDefinitionModel extends ConfigObject {
* A boolean representing if this submission definition is the default or not * A boolean representing if this submission definition is the default or not
*/ */
@autoserialize @autoserialize
isDefault: boolean; isDefault: boolean;
/** /**
* A list of SubmissionSectionModel that are present in this submission definition * A list of SubmissionSectionModel that are present in this submission definition
*/ */
// TODO refactor using remotedata // TODO refactor using remotedata
@deserialize @deserialize
sections: PaginatedList<SubmissionSectionModel>; sections: PaginatedList<SubmissionSectionModel>;
/** /**
* The links to all related resources returned by the rest api. * The links to all related resources returned by the rest api.
*/ */
@deserialize @deserialize
_links: { _links: {
self: HALLink, self: HALLink,
collections: HALLink, collections: HALLink,
sections: HALLink sections: HALLink

View File

@@ -23,5 +23,5 @@ export class SubmissionFormModel extends ConfigObject {
* An array of [FormRowModel] that are present in this form * An array of [FormRowModel] that are present in this form
*/ */
@autoserialize @autoserialize
rows: FormRowModel[]; rows: FormRowModel[];
} }

View File

@@ -22,31 +22,31 @@ export class SubmissionSectionModel extends ConfigObject {
* The header for this section * The header for this section
*/ */
@autoserialize @autoserialize
header: string; header: string;
/** /**
* A boolean representing if this submission section is the mandatory or not * A boolean representing if this submission section is the mandatory or not
*/ */
@autoserialize @autoserialize
mandatory: boolean; mandatory: boolean;
/** /**
* A string representing the kind of section object * A string representing the kind of section object
*/ */
@autoserialize @autoserialize
sectionType: SectionsType; sectionType: SectionsType;
/** /**
* The [SubmissionSectionVisibility] object for this section * The [SubmissionSectionVisibility] object for this section
*/ */
@autoserialize @autoserialize
visibility: SubmissionSectionVisibility; visibility: SubmissionSectionVisibility;
/** /**
* The {@link HALLink}s for this SubmissionSectionModel * The {@link HALLink}s for this SubmissionSectionModel
*/ */
@deserialize @deserialize
_links: { _links: {
self: HALLink; self: HALLink;
config: HALLink; config: HALLink;
}; };

View File

@@ -16,22 +16,22 @@ export class SubmissionUploadModel extends ConfigObject {
* A list of available bitstream access conditions * A list of available bitstream access conditions
*/ */
@autoserialize @autoserialize
accessConditionOptions: AccessConditionOption[]; accessConditionOptions: AccessConditionOption[];
/** /**
* An object representing the configuration describing the bitstream metadata form * An object representing the configuration describing the bitstream metadata form
*/ */
@link(SUBMISSION_FORMS_TYPE) @link(SUBMISSION_FORMS_TYPE)
metadata?: Observable<RemoteData<SubmissionFormsModel>>; metadata?: Observable<RemoteData<SubmissionFormsModel>>;
@autoserialize @autoserialize
required: boolean; required: boolean;
@autoserialize @autoserialize
maxSize: number; maxSize: number;
@deserialize @deserialize
_links: { _links: {
metadata: HALLink metadata: HALLink
self: HALLink self: HALLink
}; };

View File

@@ -23,13 +23,13 @@ export abstract class ConfigObject implements CacheableObject {
*/ */
@excludeFromEquals @excludeFromEquals
@autoserialize @autoserialize
type: ResourceType; type: ResourceType;
/** /**
* The links to all related resources returned by the rest api. * The links to all related resources returned by the rest api.
*/ */
@deserialize @deserialize
_links: { _links: {
self: HALLink, self: HALLink,
[name: string]: HALLink [name: string]: HALLink
}; };

View File

@@ -1,5 +1,5 @@
import { import {
BitstreamFormatRegistryState BitstreamFormatRegistryState
} from '../admin/admin-registries/bitstream-formats/bitstream-format.reducers'; } from '../admin/admin-registries/bitstream-formats/bitstream-format.reducers';
import { ObjectCacheState } from './cache/object-cache.reducer'; import { ObjectCacheState } from './cache/object-cache.reducer';
import { ServerSyncBufferState } from './cache/server-sync-buffer.reducer'; import { ServerSyncBufferState } from './cache/server-sync-buffer.reducer';

View File

@@ -64,7 +64,7 @@ export abstract class BaseResponseParsingService {
} else if (isRestDataObject(data._embedded[property])) { } else if (isRestDataObject(data._embedded[property])) {
object[property] = this.retrieveObjectOrUrl(parsedObj); object[property] = this.retrieveObjectOrUrl(parsedObj);
} else if (Array.isArray(parsedObj)) { } else if (Array.isArray(parsedObj)) {
object[property] = parsedObj.map((obj) => this.retrieveObjectOrUrl(obj)); object[property] = parsedObj.map((obj) => this.retrieveObjectOrUrl(obj));
} }
} }
}); });
@@ -102,8 +102,8 @@ export abstract class BaseResponseParsingService {
protected processArray<ObjectDomain>(data: any, request: RestRequest): ObjectDomain[] { protected processArray<ObjectDomain>(data: any, request: RestRequest): ObjectDomain[] {
let array: ObjectDomain[] = []; let array: ObjectDomain[] = [];
data.forEach((datum) => { data.forEach((datum) => {
array = [...array, this.process(datum, request)]; array = [...array, this.process(datum, request)];
} }
); );
return array; return array;
} }

View File

@@ -373,10 +373,10 @@ export class BaseDataService<T extends CacheableObject> implements HALDataServic
return this.hasCachedResponse(href$).pipe( return this.hasCachedResponse(href$).pipe(
switchMap((hasCachedResponse) => { switchMap((hasCachedResponse) => {
if (hasCachedResponse) { if (hasCachedResponse) {
return this.rdbService.buildSingle(href$).pipe( return this.rdbService.buildSingle(href$).pipe(
getFirstCompletedRemoteData(), getFirstCompletedRemoteData(),
map((rd => rd.hasFailed)) map((rd => rd.hasFailed))
); );
} }
return observableOf(false); return observableOf(false);
}) })

View File

@@ -143,8 +143,8 @@ describe('FindAllDataImpl', () => {
options = {}; options = {};
(service as any).getFindAllHref(options).subscribe((value) => { (service as any).getFindAllHref(options).subscribe((value) => {
expect(value).toBe(endpoint); expect(value).toBe(endpoint);
}, },
); );
}); });

View File

@@ -26,22 +26,22 @@ describe('BrowseResponseParsingService', () => {
describe('', () => { describe('', () => {
const mockFlatBrowse = { const mockFlatBrowse = {
id: 'title', id: 'title',
browseType: 'flatBrowse', browseType: 'flatBrowse',
type: 'browse', type: 'browse',
}; };
const mockValueList = { const mockValueList = {
id: 'author', id: 'author',
browseType: 'valueList', browseType: 'valueList',
type: 'browse', type: 'browse',
}; };
const mockHierarchicalBrowse = { const mockHierarchicalBrowse = {
id: 'srsc', id: 'srsc',
browseType: 'hierarchicalBrowse', browseType: 'hierarchicalBrowse',
type: 'browse', type: 'browse',
}; };
it('should deserialize flatBrowses correctly', () => { it('should deserialize flatBrowses correctly', () => {
let deserialized = service.deserialize(mockFlatBrowse); let deserialized = service.deserialize(mockFlatBrowse);

View File

@@ -42,7 +42,7 @@ class DsoByIdOrUUIDDataService extends IdentifiableDataService<DSpaceObject> {
// interpolate id/uuid as query parameter // interpolate id/uuid as query parameter
(endpoint: string, resourceID: string): string => { (endpoint: string, resourceID: string): string => {
return endpoint.replace(/{\?id}/, `?id=${resourceID}`) return endpoint.replace(/{\?id}/, `?id=${resourceID}`)
.replace(/{\?uuid}/, `?uuid=${resourceID}`); .replace(/{\?uuid}/, `?uuid=${resourceID}`);
}, },
); );
} }

View File

@@ -184,8 +184,8 @@ export class DspaceRestResponseParsingService implements ResponseParsingService
protected processArray<ObjectDomain>(data: any, request: RestRequest): ObjectDomain[] { protected processArray<ObjectDomain>(data: any, request: RestRequest): ObjectDomain[] {
let array: ObjectDomain[] = []; let array: ObjectDomain[] = [];
data.forEach((datum) => { data.forEach((datum) => {
array = [...array, this.process(datum, request)]; array = [...array, this.process(datum, request)];
} }
); );
return array; return array;
} }

View File

@@ -11,17 +11,17 @@ import { FeatureID } from '../feature-id';
* management rights * management rights
*/ */
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class StatisticsAdministratorGuard extends SingleFeatureAuthorizationGuard { export class StatisticsAdministratorGuard extends SingleFeatureAuthorizationGuard {
constructor(protected authorizationService: AuthorizationDataService, protected router: Router, protected authService: AuthService) { constructor(protected authorizationService: AuthorizationDataService, protected router: Router, protected authService: AuthService) {
super(authorizationService, router, authService); super(authorizationService, router, authService);
} }
/** /**
* Check group management rights * Check group management rights
*/ */
getFeatureID(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<FeatureID> { getFeatureID(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<FeatureID> {
return observableOf(FeatureID.CanViewUsageStatistics); return observableOf(FeatureID.CanViewUsageStatistics);
} }
} }

View File

@@ -5,11 +5,11 @@ import { RequestParam } from '../cache/models/request-param.model';
* The options for a find list request * The options for a find list request
*/ */
export class FindListOptions { export class FindListOptions {
scopeID?: string; scopeID?: string;
elementsPerPage?: number; elementsPerPage?: number;
currentPage?: number; currentPage?: number;
sort?: SortOptions; sort?: SortOptions;
searchParams?: RequestParam[]; searchParams?: RequestParam[];
startsWith?: string; startsWith?: string;
fetchThumbnail?: boolean; fetchThumbnail?: boolean;
} }

View File

@@ -23,60 +23,60 @@ describe(`HrefOnlyDataService`, () => {
expect((service as any).dataService).toBeInstanceOf(BaseDataService); expect((service as any).dataService).toBeInstanceOf(BaseDataService);
}); });
describe(`findByHref`, () => { describe(`findByHref`, () => {
beforeEach(() => { beforeEach(() => {
spy = spyOn((service as any).dataService, 'findByHref').and.returnValue(createSuccessfulRemoteDataObject$(null)); spy = spyOn((service as any).dataService, 'findByHref').and.returnValue(createSuccessfulRemoteDataObject$(null));
}); });
it(`should forward to findByHref on the internal DataService`, () => { it(`should forward to findByHref on the internal DataService`, () => {
service.findByHref(href, false, false, ...followLinks); service.findByHref(href, false, false, ...followLinks);
expect(spy).toHaveBeenCalledWith(href, false, false, ...followLinks); expect(spy).toHaveBeenCalledWith(href, false, false, ...followLinks);
}); });
describe(`when useCachedVersionIfAvailable is omitted`, () => { describe(`when useCachedVersionIfAvailable is omitted`, () => {
it(`should call findByHref on the internal DataService with useCachedVersionIfAvailable = true`, () => { it(`should call findByHref on the internal DataService with useCachedVersionIfAvailable = true`, () => {
service.findByHref(href); service.findByHref(href);
expect(spy).toHaveBeenCalledWith(jasmine.anything(), true, jasmine.anything()); expect(spy).toHaveBeenCalledWith(jasmine.anything(), true, jasmine.anything());
});
});
describe(`when reRequestOnStale is omitted`, () => {
it(`should call findByHref on the internal DataService with reRequestOnStale = true`, () => {
service.findByHref(href);
expect(spy).toHaveBeenCalledWith(jasmine.anything(), jasmine.anything(), true);
});
}); });
}); });
describe(`findListByHref`, () => { describe(`when reRequestOnStale is omitted`, () => {
beforeEach(() => { it(`should call findByHref on the internal DataService with reRequestOnStale = true`, () => {
spy = spyOn((service as any).dataService, 'findListByHref').and.returnValue(createSuccessfulRemoteDataObject$(null)); service.findByHref(href);
}); expect(spy).toHaveBeenCalledWith(jasmine.anything(), jasmine.anything(), true);
it(`should delegate to findListByHref on the internal DataService`, () => {
service.findListByHref(href, findListOptions, false, false, ...followLinks);
expect(spy).toHaveBeenCalledWith(href, findListOptions, false, false, ...followLinks);
});
describe(`when findListOptions is omitted`, () => {
it(`should call findListByHref on the internal DataService with findListOptions = {}`, () => {
service.findListByHref(href);
expect(spy).toHaveBeenCalledWith(jasmine.anything(), {}, jasmine.anything(), jasmine.anything());
});
});
describe(`when useCachedVersionIfAvailable is omitted`, () => {
it(`should call findListByHref on the internal DataService with useCachedVersionIfAvailable = true`, () => {
service.findListByHref(href);
expect(spy).toHaveBeenCalledWith(jasmine.anything(), jasmine.anything(), true, jasmine.anything());
});
});
describe(`when reRequestOnStale is omitted`, () => {
it(`should call findListByHref on the internal DataService with reRequestOnStale = true`, () => {
service.findListByHref(href);
expect(spy).toHaveBeenCalledWith(jasmine.anything(), jasmine.anything(), jasmine.anything(), true);
});
}); });
}); });
});
describe(`findListByHref`, () => {
beforeEach(() => {
spy = spyOn((service as any).dataService, 'findListByHref').and.returnValue(createSuccessfulRemoteDataObject$(null));
});
it(`should delegate to findListByHref on the internal DataService`, () => {
service.findListByHref(href, findListOptions, false, false, ...followLinks);
expect(spy).toHaveBeenCalledWith(href, findListOptions, false, false, ...followLinks);
});
describe(`when findListOptions is omitted`, () => {
it(`should call findListByHref on the internal DataService with findListOptions = {}`, () => {
service.findListByHref(href);
expect(spy).toHaveBeenCalledWith(jasmine.anything(), {}, jasmine.anything(), jasmine.anything());
});
});
describe(`when useCachedVersionIfAvailable is omitted`, () => {
it(`should call findListByHref on the internal DataService with useCachedVersionIfAvailable = true`, () => {
service.findListByHref(href);
expect(spy).toHaveBeenCalledWith(jasmine.anything(), jasmine.anything(), true, jasmine.anything());
});
});
describe(`when reRequestOnStale is omitted`, () => {
it(`should call findListByHref on the internal DataService with reRequestOnStale = true`, () => {
service.findListByHref(href);
expect(spy).toHaveBeenCalledWith(jasmine.anything(), jasmine.anything(), jasmine.anything(), true);
});
});
});
}); });

View File

@@ -85,8 +85,8 @@ describe('ObjectUpdatesEffects', () => {
updatesEffects.removeAfterDiscardOrReinstateOnUndo$.pipe( updatesEffects.removeAfterDiscardOrReinstateOnUndo$.pipe(
filter(((action) => hasValue(action)))) filter(((action) => hasValue(action))))
.subscribe((t) => { .subscribe((t) => {
expect(t).toEqual(removeAction); expect(t).toEqual(removeAction);
} }
) )
; ;
}); });
@@ -101,8 +101,8 @@ describe('ObjectUpdatesEffects', () => {
actions = hot('a', { a: new DiscardObjectUpdatesAction(testURL, infoNotification) }); actions = hot('a', { a: new DiscardObjectUpdatesAction(testURL, infoNotification) });
actions = hot('b', { b: new ReinstateObjectUpdatesAction(testURL) }); actions = hot('b', { b: new ReinstateObjectUpdatesAction(testURL) });
updatesEffects.removeAfterDiscardOrReinstateOnUndo$.subscribe((t) => { updatesEffects.removeAfterDiscardOrReinstateOnUndo$.subscribe((t) => {
expect(t).toEqual(new NoOpAction()); expect(t).toEqual(new NoOpAction());
} }
); );
}); });
}); });

View File

@@ -52,7 +52,7 @@ export class ObjectUpdatesEffects {
/** /**
* Effect that makes sure all last fired ObjectUpdatesActions are stored in the map of this service, with the url as their key * Effect that makes sure all last fired ObjectUpdatesActions are stored in the map of this service, with the url as their key
*/ */
mapLastActions$ = createEffect(() => this.actions$ mapLastActions$ = createEffect(() => this.actions$
.pipe( .pipe(
ofType(...Object.values(ObjectUpdatesActionTypes)), ofType(...Object.values(ObjectUpdatesActionTypes)),
map((action: ObjectUpdatesAction) => { map((action: ObjectUpdatesAction) => {
@@ -69,16 +69,16 @@ export class ObjectUpdatesEffects {
/** /**
* Effect that makes sure all last fired NotificationActions are stored in the notification map of this service, with the id as their key * Effect that makes sure all last fired NotificationActions are stored in the notification map of this service, with the id as their key
*/ */
mapLastNotificationActions$ = createEffect(() => this.actions$ mapLastNotificationActions$ = createEffect(() => this.actions$
.pipe( .pipe(
ofType(...Object.values(NotificationsActionTypes)), ofType(...Object.values(NotificationsActionTypes)),
map((action: RemoveNotificationAction) => { map((action: RemoveNotificationAction) => {
const id: string = action.payload.id || action.payload || this.allIdentifier; const id: string = action.payload.id || action.payload || this.allIdentifier;
if (hasNoValue(this.notificationActionMap$[id])) { if (hasNoValue(this.notificationActionMap$[id])) {
this.notificationActionMap$[id] = new Subject<NotificationsActions>(); this.notificationActionMap$[id] = new Subject<NotificationsActions>();
}
this.notificationActionMap$[id].next(action);
} }
this.notificationActionMap$[id].next(action);
}
) )
), { dispatch: false }); ), { dispatch: false });
@@ -88,51 +88,51 @@ export class ObjectUpdatesEffects {
* When a REINSTATE action is fired during the timeout, a NO_ACTION action will be returned * When a REINSTATE action is fired during the timeout, a NO_ACTION action will be returned
* When any other ObjectUpdatesAction is fired during the timeout, a RemoteObjectUpdatesAction will be returned * When any other ObjectUpdatesAction is fired during the timeout, a RemoteObjectUpdatesAction will be returned
*/ */
removeAfterDiscardOrReinstateOnUndo$ = createEffect(() => this.actions$ removeAfterDiscardOrReinstateOnUndo$ = createEffect(() => this.actions$
.pipe( .pipe(
ofType(ObjectUpdatesActionTypes.DISCARD), ofType(ObjectUpdatesActionTypes.DISCARD),
switchMap((action: DiscardObjectUpdatesAction) => { switchMap((action: DiscardObjectUpdatesAction) => {
const url: string = action.payload.url; const url: string = action.payload.url;
const notification: INotification = action.payload.notification; const notification: INotification = action.payload.notification;
const timeOut = notification.options.timeOut; const timeOut = notification.options.timeOut;
let removeAction: Action = new RemoveObjectUpdatesAction(action.payload.url); let removeAction: Action = new RemoveObjectUpdatesAction(action.payload.url);
if (action.payload.discardAll) { if (action.payload.discardAll) {
removeAction = new RemoveAllObjectUpdatesAction(); removeAction = new RemoveAllObjectUpdatesAction();
}
return observableRace(
// Either wait for the delay and perform a remove action
observableOf(removeAction).pipe(delay(timeOut)),
// Or wait for a a user action
this.actionMap$[url].pipe(
take(1),
tap(() => {
this.notificationsService.remove(notification);
}),
map((updateAction: ObjectUpdatesAction) => {
if (updateAction.type === ObjectUpdatesActionTypes.REINSTATE) {
// If someone reinstated, do nothing, just let the reinstating happen
return new NoOpAction();
}
// If someone performed another action, assume the user does not want to reinstate and remove all changes
return removeAction;
})
),
this.notificationActionMap$[notification.id].pipe(
filter((notificationsAction: NotificationsActions) => notificationsAction.type === NotificationsActionTypes.REMOVE_NOTIFICATION),
map(() => {
return removeAction;
})
),
this.notificationActionMap$[this.allIdentifier].pipe(
filter((notificationsAction: NotificationsActions) => notificationsAction.type === NotificationsActionTypes.REMOVE_ALL_NOTIFICATIONS),
map(() => {
return removeAction;
})
)
);
} }
return observableRace(
// Either wait for the delay and perform a remove action
observableOf(removeAction).pipe(delay(timeOut)),
// Or wait for a a user action
this.actionMap$[url].pipe(
take(1),
tap(() => {
this.notificationsService.remove(notification);
}),
map((updateAction: ObjectUpdatesAction) => {
if (updateAction.type === ObjectUpdatesActionTypes.REINSTATE) {
// If someone reinstated, do nothing, just let the reinstating happen
return new NoOpAction();
}
// If someone performed another action, assume the user does not want to reinstate and remove all changes
return removeAction;
})
),
this.notificationActionMap$[notification.id].pipe(
filter((notificationsAction: NotificationsActions) => notificationsAction.type === NotificationsActionTypes.REMOVE_NOTIFICATION),
map(() => {
return removeAction;
})
),
this.notificationActionMap$[this.allIdentifier].pipe(
filter((notificationsAction: NotificationsActions) => notificationsAction.type === NotificationsActionTypes.REMOVE_ALL_NOTIFICATIONS),
map(() => {
return removeAction;
})
)
);
}
) )
)); ));

View File

@@ -139,16 +139,16 @@ export class ObjectUpdatesService {
return objectUpdates.pipe( return objectUpdates.pipe(
hasValueOperator(), hasValueOperator(),
map((objectEntry) => { map((objectEntry) => {
const fieldUpdates: FieldUpdates = {}; const fieldUpdates: FieldUpdates = {};
for (const object of initialFields) { for (const object of initialFields) {
let fieldUpdate = objectEntry.fieldUpdates[object.uuid]; let fieldUpdate = objectEntry.fieldUpdates[object.uuid];
if (isEmpty(fieldUpdate)) { if (isEmpty(fieldUpdate)) {
fieldUpdate = { field: object, changeType: undefined }; fieldUpdate = { field: object, changeType: undefined };
}
fieldUpdates[object.uuid] = fieldUpdate;
} }
fieldUpdates[object.uuid] = fieldUpdate; return fieldUpdates;
} }));
return fieldUpdates;
}));
} }
/** /**
@@ -234,7 +234,7 @@ export class ObjectUpdatesService {
.pipe( .pipe(
select(virtualMetadataSourceSelector(url, relationship)), select(virtualMetadataSourceSelector(url, relationship)),
map((virtualMetadataSource) => virtualMetadataSource && virtualMetadataSource[item]), map((virtualMetadataSource) => virtualMetadataSource && virtualMetadataSource[item]),
); );
} }
/** /**

View File

@@ -64,13 +64,13 @@ export class PaginatedList<T> extends CacheableObject {
* The type of the list * The type of the list
*/ */
@excludeFromEquals @excludeFromEquals
type = PAGINATED_LIST; type = PAGINATED_LIST;
/** /**
* The type of objects in the list * The type of objects in the list
*/ */
@autoserialize @autoserialize
objectType?: ResourceType; objectType?: ResourceType;
/** /**
* The list of objects that represents the current page * The list of objects that represents the current page
@@ -81,13 +81,13 @@ export class PaginatedList<T> extends CacheableObject {
* the {@link PageInfo} object * the {@link PageInfo} object
*/ */
@autoserialize @autoserialize
pageInfo?: PageInfo; pageInfo?: PageInfo;
/** /**
* The {@link HALLink}s for this PaginatedList * The {@link HALLink}s for this PaginatedList
*/ */
@deserialize @deserialize
_links: { _links: {
self: HALLink; self: HALLink;
page: HALLink[]; page: HALLink[];
first?: HALLink; first?: HALLink;

View File

@@ -64,7 +64,7 @@ export class PrimaryBitstreamService {
endpointURL, endpointURL,
primaryBitstreamSelfLink, primaryBitstreamSelfLink,
this.getHttpOptions() this.getHttpOptions()
); );
this.requestService.send(request); this.requestService.send(request);

View File

@@ -264,7 +264,7 @@ describe('RelationshipDataService', () => {
authority: 'virtual::related-creator', authority: 'virtual::related-creator',
place: 3, place: 3,
}), }),
Object.assign(new MetadataValue(), { Object.assign(new MetadataValue(), {
language: null, language: null,
value: 'Related Creator with authority - unauthorized', value: 'Related Creator with authority - unauthorized',
authority: 'virtual::related-creator-unauthorized', authority: 'virtual::related-creator-unauthorized',

View File

@@ -169,7 +169,7 @@ export class RelationshipDataService extends IdentifiableDataService<Relationshi
switchMap((rel: Relationship) => observableCombineLatest( switchMap((rel: Relationship) => observableCombineLatest(
rel.leftItem.pipe(getFirstSucceededRemoteData(), getRemoteDataPayload()), rel.leftItem.pipe(getFirstSucceededRemoteData(), getRemoteDataPayload()),
rel.rightItem.pipe(getFirstSucceededRemoteData(), getRemoteDataPayload()) rel.rightItem.pipe(getFirstSucceededRemoteData(), getRemoteDataPayload())
) )
), ),
take(1) take(1)
).subscribe(([item1, item2]) => { ).subscribe(([item1, item2]) => {
@@ -237,7 +237,7 @@ export class RelationshipDataService extends IdentifiableDataService<Relationshi
return relationshipType.rightwardType; return relationshipType.rightwardType;
} }
}) })
) )
)); ));
} }
@@ -346,21 +346,21 @@ export class RelationshipDataService extends IdentifiableDataService<Relationshi
followLink('leftItem'), followLink('leftItem'),
followLink('rightItem') followLink('rightItem')
).pipe( ).pipe(
getFirstSucceededRemoteData(), getFirstSucceededRemoteData(),
// the mergemap below will emit all elements of the list as separate events // the mergemap below will emit all elements of the list as separate events
mergeMap((relationshipListRD: RemoteData<PaginatedList<Relationship>>) => relationshipListRD.payload.page), mergeMap((relationshipListRD: RemoteData<PaginatedList<Relationship>>) => relationshipListRD.payload.page),
mergeMap((relationship: Relationship) => { mergeMap((relationship: Relationship) => {
return observableCombineLatest([ return observableCombineLatest([
this.itemService.findByHref(relationship._links.leftItem.href).pipe(compareItemsByUUID(item2)), this.itemService.findByHref(relationship._links.leftItem.href).pipe(compareItemsByUUID(item2)),
this.itemService.findByHref(relationship._links.rightItem.href).pipe(compareItemsByUUID(item2)) this.itemService.findByHref(relationship._links.rightItem.href).pipe(compareItemsByUUID(item2))
]).pipe( ]).pipe(
map(([isLeftItem, isRightItem]) => isLeftItem || isRightItem), map(([isLeftItem, isRightItem]) => isLeftItem || isRightItem),
map((isMatch) => isMatch ? relationship : undefined) map((isMatch) => isMatch ? relationship : undefined)
); );
}), }),
filter((relationship) => hasValue(relationship)), filter((relationship) => hasValue(relationship)),
take(1) take(1)
); );
} }
/** /**
@@ -494,31 +494,31 @@ export class RelationshipDataService extends IdentifiableDataService<Relationshi
searchByItemsAndType(typeId: string,itemUuid: string,relationshipLabel: string, arrayOfItemIds: string[] ): Observable<RemoteData<PaginatedList<Relationship>>> { searchByItemsAndType(typeId: string,itemUuid: string,relationshipLabel: string, arrayOfItemIds: string[] ): Observable<RemoteData<PaginatedList<Relationship>>> {
const searchParams = [ const searchParams = [
{ {
fieldName: 'typeId', fieldName: 'typeId',
fieldValue: typeId fieldValue: typeId
}, },
{ {
fieldName: 'focusItem', fieldName: 'focusItem',
fieldValue: itemUuid fieldValue: itemUuid
}, },
{ {
fieldName: 'relationshipLabel', fieldName: 'relationshipLabel',
fieldValue: relationshipLabel fieldValue: relationshipLabel
}, },
{ {
fieldName: 'size', fieldName: 'size',
fieldValue: arrayOfItemIds.length fieldValue: arrayOfItemIds.length
}, },
{ {
fieldName: 'embed', fieldName: 'embed',
fieldValue: 'leftItem' fieldValue: 'leftItem'
}, },
{ {
fieldName: 'embed', fieldName: 'embed',
fieldValue: 'rightItem' fieldValue: 'rightItem'
}, },
]; ];
arrayOfItemIds.forEach( (itemId) => { arrayOfItemIds.forEach( (itemId) => {
searchParams.push( searchParams.push(

View File

@@ -62,33 +62,33 @@ export class RelationshipTypeDataService extends BaseDataService<RelationshipTyp
getRelationshipTypeByLabelAndTypes(relationshipTypeLabel: string, firstItemType: string, secondItemType: string): Observable<RelationshipType> { getRelationshipTypeByLabelAndTypes(relationshipTypeLabel: string, firstItemType: string, secondItemType: string): Observable<RelationshipType> {
// Retrieve all relationship types from the server in a single page // Retrieve all relationship types from the server in a single page
return this.findAllData.findAll({ currentPage: 1, elementsPerPage: 9999 }, true, true, followLink('leftType'), followLink('rightType')) return this.findAllData.findAll({ currentPage: 1, elementsPerPage: 9999 }, true, true, followLink('leftType'), followLink('rightType'))
.pipe( .pipe(
getFirstSucceededRemoteData(), getFirstSucceededRemoteData(),
// Emit each type in the page array separately // Emit each type in the page array separately
switchMap((typeListRD: RemoteData<PaginatedList<RelationshipType>>) => typeListRD.payload.page), switchMap((typeListRD: RemoteData<PaginatedList<RelationshipType>>) => typeListRD.payload.page),
// Check each type individually, to see if it matches the provided types // Check each type individually, to see if it matches the provided types
mergeMap((relationshipType: RelationshipType) => { mergeMap((relationshipType: RelationshipType) => {
if (relationshipType.leftwardType === relationshipTypeLabel) { if (relationshipType.leftwardType === relationshipTypeLabel) {
return this.checkType(relationshipType, firstItemType, secondItemType); return this.checkType(relationshipType, firstItemType, secondItemType);
} else if (relationshipType.rightwardType === relationshipTypeLabel) { } else if (relationshipType.rightwardType === relationshipTypeLabel) {
return this.checkType(relationshipType, secondItemType, firstItemType); return this.checkType(relationshipType, secondItemType, firstItemType);
} else { } else {
return [null]; return [null];
} }
}), }),
// Wait for all types to be checked and emit once, with the results combined back into an // Wait for all types to be checked and emit once, with the results combined back into an
// array // array
toArray(), toArray(),
// Look for a match in the array and emit it if found, or null if one isn't found // Look for a match in the array and emit it if found, or null if one isn't found
map((types: RelationshipType[]) => { map((types: RelationshipType[]) => {
const match = types.find((type: RelationshipType) => hasValue(type)); const match = types.find((type: RelationshipType) => hasValue(type));
if (hasValue(match)) { if (hasValue(match)) {
return match; return match;
} else { } else {
return null; return null;
} }
}), }),
); );
} }
/** /**

View File

@@ -6,8 +6,8 @@ import { ResponseState } from './response-state.model';
* An entry for a request in the NgRx store * An entry for a request in the NgRx store
*/ */
export class RequestEntry { export class RequestEntry {
request: RestRequestWithResponseParser; request: RestRequestWithResponseParser;
state: RequestEntryState; state: RequestEntryState;
response: ResponseState; response: ResponseState;
lastUpdated: number; lastUpdated: number;
} }

View File

@@ -25,7 +25,7 @@ import { RequestEntry } from './request-entry.model';
@Injectable() @Injectable()
export class RequestEffects { export class RequestEffects {
execute = createEffect(() => this.actions$.pipe( execute = createEffect(() => this.actions$.pipe(
ofType(RequestActionTypes.EXECUTE), ofType(RequestActionTypes.EXECUTE),
mergeMap((action: RequestExecuteAction) => { mergeMap((action: RequestExecuteAction) => {
return this.requestService.getByUUID(action.payload).pipe( return this.requestService.getByUUID(action.payload).pipe(
@@ -64,7 +64,7 @@ export class RequestEffects {
* This assumes that the server cached everything a negligible * This assumes that the server cached everything a negligible
* time ago, and will likely need to be revisited later * time ago, and will likely need to be revisited later
*/ */
fixTimestampsOnRehydrate = createEffect(() => this.actions$ fixTimestampsOnRehydrate = createEffect(() => this.actions$
.pipe(ofType(StoreActionTypes.REHYDRATE), .pipe(ofType(StoreActionTypes.REHYDRATE),
map(() => new ResetResponseTimestampsAction(new Date().getTime())) map(() => new ResetResponseTimestampsAction(new Date().getTime()))
)); ));

View File

@@ -188,14 +188,14 @@ export class RequestService {
private fixRequestHeaders() { private fixRequestHeaders() {
return (source: Observable<RequestEntry>): Observable<RequestEntry> => { return (source: Observable<RequestEntry>): Observable<RequestEntry> => {
return source.pipe(map((entry: RequestEntry) => { return source.pipe(map((entry: RequestEntry) => {
// Headers break after being retrieved from the store (because of lazy initialization) // Headers break after being retrieved from the store (because of lazy initialization)
// Combining them with a new object fixes this issue // Combining them with a new object fixes this issue
if (hasValue(entry) && hasValue(entry.request) && hasValue(entry.request.options) && hasValue(entry.request.options.headers)) { if (hasValue(entry) && hasValue(entry.request) && hasValue(entry.request.options) && hasValue(entry.request.options.headers)) {
entry = cloneDeep(entry); entry = cloneDeep(entry);
entry.request.options.headers = Object.assign(new HttpHeaders(), entry.request.options.headers); entry.request.options.headers = Object.assign(new HttpHeaders(), entry.request.options.headers);
} }
return entry; return entry;
}) })
); );
}; };
} }
@@ -331,7 +331,7 @@ export class RequestService {
map((request: RequestEntry) => isStale(request.state)), map((request: RequestEntry) => isStale(request.state)),
filter((stale: boolean) => stale), filter((stale: boolean) => stale),
take(1), take(1),
); );
} }
/** /**

View File

@@ -5,9 +5,9 @@ import { UnCacheableObject } from '../shared/uncacheable-object.model';
* The response substate in the NgRx store * The response substate in the NgRx store
*/ */
export class ResponseState { export class ResponseState {
timeCompleted: number; timeCompleted: number;
statusCode: number; statusCode: number;
errorMessage?: string; errorMessage?: string;
payloadLink?: HALLink; payloadLink?: HALLink;
unCacheableObject?: UnCacheableObject; unCacheableObject?: UnCacheableObject;
} }

View File

@@ -6,15 +6,15 @@ import { HttpOptions } from '../dspace-rest/dspace-rest.service';
* A request to the DSpace REST API * A request to the DSpace REST API
*/ */
export abstract class RestRequest { export abstract class RestRequest {
public responseMsToLive = environment.cache.msToLive.default; public responseMsToLive = environment.cache.msToLive.default;
public isMultipart = false; public isMultipart = false;
constructor( constructor(
public uuid: string, public uuid: string,
public href: string, public href: string,
public method: RestRequestMethod = RestRequestMethod.GET, public method: RestRequestMethod = RestRequestMethod.GET,
public body?: any, public body?: any,
public options?: HttpOptions, public options?: HttpOptions,
) { ) {
} }
} }

View File

@@ -18,37 +18,37 @@ export class Root implements CacheableObject {
*/ */
@excludeFromEquals @excludeFromEquals
@autoserialize @autoserialize
type: ResourceType; type: ResourceType;
/** /**
* The url for the dspace UI * The url for the dspace UI
*/ */
@autoserialize @autoserialize
dspaceUI: string; dspaceUI: string;
/** /**
* The repository Name * The repository Name
*/ */
@autoserialize @autoserialize
dspaceName: string; dspaceName: string;
/** /**
* The url for the rest api * The url for the rest api
*/ */
@autoserialize @autoserialize
dspaceServer: string; dspaceServer: string;
/** /**
* The current DSpace version * The current DSpace version
*/ */
@autoserialize @autoserialize
dspaceVersion: string; dspaceVersion: string;
/** /**
* The {@link HALLink}s for the root object * The {@link HALLink}s for the root object
*/ */
@deserialize @deserialize
_links: { _links: {
self: HALLink; self: HALLink;
[k: string]: HALLink | HALLink[]; [k: string]: HALLink | HALLink[];
}; };

View File

@@ -5,13 +5,13 @@ import { DSpaceSerializer } from './dspace.serializer';
class TestModel implements HALResource { class TestModel implements HALResource {
@autoserialize @autoserialize
id: string; id: string;
@autoserialize @autoserialize
name: string; name: string;
@deserialize @deserialize
_links: { _links: {
self: HALLink; self: HALLink;
parents: HALLink; parents: HALLink;
}; };

View File

@@ -5,17 +5,17 @@ import { EPerson } from './eperson.model';
*/ */
export class EpersonDtoModel { export class EpersonDtoModel {
/** /**
* The EPerson linked to this object * The EPerson linked to this object
*/ */
public eperson: EPerson; public eperson: EPerson;
/** /**
* Whether or not the linked EPerson is able to be deleted * Whether or not the linked EPerson is able to be deleted
*/ */
public ableToDelete: boolean; public ableToDelete: boolean;
/** /**
* Whether or not this EPerson is member of group on page it is being used on * Whether or not this EPerson is member of group on page it is being used on
*/ */
public memberOfGroup: boolean; public memberOfGroup: boolean;
} }

View File

@@ -40,7 +40,7 @@ export class Group extends DSpaceObject {
* The {@link HALLink}s for this Group * The {@link HALLink}s for this Group
*/ */
@deserialize @deserialize
_links: { _links: {
self: HALLink; self: HALLink;
subgroups: HALLink; subgroups: HALLink;
epersons: HALLink; epersons: HALLink;

View File

@@ -24,7 +24,7 @@ import { CoreState } from '../core-state.model';
@Injectable() @Injectable()
export class UUIDIndexEffects { export class UUIDIndexEffects {
addObject$ = createEffect(() => this.actions$ addObject$ = createEffect(() => this.actions$
.pipe( .pipe(
ofType(ObjectCacheActionTypes.ADD), ofType(ObjectCacheActionTypes.ADD),
filter((action: AddToObjectCacheAction) => hasValue(action.payload.objectToCache.uuid)), filter((action: AddToObjectCacheAction) => hasValue(action.payload.objectToCache.uuid)),
@@ -41,7 +41,7 @@ export class UUIDIndexEffects {
* Adds an alternative link to an object to the ALTERNATIVE_OBJECT_LINK index * Adds an alternative link to an object to the ALTERNATIVE_OBJECT_LINK index
* When the self link of the objectToCache is not the same as the alternativeLink * When the self link of the objectToCache is not the same as the alternativeLink
*/ */
addAlternativeObjectLink$ = createEffect(() => this.actions$ addAlternativeObjectLink$ = createEffect(() => this.actions$
.pipe( .pipe(
ofType(ObjectCacheActionTypes.ADD), ofType(ObjectCacheActionTypes.ADD),
map((action: AddToObjectCacheAction) => { map((action: AddToObjectCacheAction) => {
@@ -59,7 +59,7 @@ export class UUIDIndexEffects {
}) })
)); ));
removeObject$ = createEffect(() => this.actions$ removeObject$ = createEffect(() => this.actions$
.pipe( .pipe(
ofType(ObjectCacheActionTypes.REMOVE), ofType(ObjectCacheActionTypes.REMOVE),
map((action: RemoveFromObjectCacheAction) => { map((action: RemoveFromObjectCacheAction) => {
@@ -70,18 +70,18 @@ export class UUIDIndexEffects {
}) })
)); ));
addRequest$ = createEffect(() => this.actions$ addRequest$ = createEffect(() => this.actions$
.pipe( .pipe(
ofType(RequestActionTypes.CONFIGURE), ofType(RequestActionTypes.CONFIGURE),
filter((action: RequestConfigureAction) => action.payload.method === RestRequestMethod.GET), filter((action: RequestConfigureAction) => action.payload.method === RestRequestMethod.GET),
switchMap((action: RequestConfigureAction) => { switchMap((action: RequestConfigureAction) => {
const href = getUrlWithoutEmbedParams(action.payload.href); const href = getUrlWithoutEmbedParams(action.payload.href);
return this.store.pipe( return this.store.pipe(
select(uuidFromHrefSelector(href)), select(uuidFromHrefSelector(href)),
take(1), take(1),
map((uuid: string) => [action, uuid]) map((uuid: string) => [action, uuid])
); );
} }
), ),
switchMap(([action, uuid]: [RequestConfigureAction, string]) => { switchMap(([action, uuid]: [RequestConfigureAction, string]) => {
let actions = []; let actions = [];

View File

@@ -17,7 +17,7 @@ export class JsonPatchOperationsEffects {
/** /**
* Dispatches a FlushPatchOperationsAction for every dispatched CommitPatchOperationsAction * Dispatches a FlushPatchOperationsAction for every dispatched CommitPatchOperationsAction
*/ */
commit$ = createEffect(() => this.actions$.pipe( commit$ = createEffect(() => this.actions$.pipe(
ofType(JsonPatchOperationsActionTypes.COMMIT_JSON_PATCH_OPERATIONS), ofType(JsonPatchOperationsActionTypes.COMMIT_JSON_PATCH_OPERATIONS),
map((action: CommitPatchOperationsAction) => { map((action: CommitPatchOperationsAction) => {
return new FlushPatchOperationsAction(action.payload.resourceType, action.payload.resourceId); return new FlushPatchOperationsAction(action.payload.resourceType, action.payload.resourceId);

View File

@@ -100,7 +100,7 @@ export abstract class JsonPatchOperationsService<ResponseDefinitionDomain, Patch
} }
}), }),
distinctUntilChanged() distinctUntilChanged()
); );
})) }))
); );
} }

View File

@@ -80,7 +80,7 @@ export class LocaleService {
mergeMap(([isAuthenticated, isLoaded]) => { mergeMap(([isAuthenticated, isLoaded]) => {
// TODO to enabled again when https://github.com/DSpace/dspace-angular/issues/739 will be resolved // TODO to enabled again when https://github.com/DSpace/dspace-angular/issues/739 will be resolved
const epersonLang$: Observable<string[]> = observableOf([]); const epersonLang$: Observable<string[]> = observableOf([]);
/* if (isAuthenticated && isLoaded) { /* if (isAuthenticated && isLoaded) {
epersonLang$ = this.authService.getAuthenticatedUserFromStore().pipe( epersonLang$ = this.authService.getAuthenticatedUserFromStore().pipe(
take(1), take(1),
map((eperson) => { map((eperson) => {
@@ -176,11 +176,11 @@ export class LocaleService {
divisor = 1; divisor = 1;
} }
languages.forEach( (lang) => { languages.forEach( (lang) => {
let value = lang + ';q='; let value = lang + ';q=';
let quality = (v - idx++) / v; let quality = (v - idx++) / v;
quality = ((languages.length > 10) ? quality.toFixed(2) : quality) as number; quality = ((languages.length > 10) ? quality.toFixed(2) : quality) as number;
value += quality / divisor; value += quality / divisor;
langWithPrior.push(value); langWithPrior.push(value);
}); });
return langWithPrior; return langWithPrior;
} }

View File

@@ -25,37 +25,37 @@ export class MetadataField extends ListableObject implements HALResource {
*/ */
@excludeFromEquals @excludeFromEquals
@autoserialize @autoserialize
type: ResourceType; type: ResourceType;
/** /**
* The identifier of this metadata field * The identifier of this metadata field
*/ */
@autoserialize @autoserialize
id: number; id: number;
/** /**
* The element of this metadata field * The element of this metadata field
*/ */
@autoserialize @autoserialize
element: string; element: string;
/** /**
* The qualifier of this metadata field * The qualifier of this metadata field
*/ */
@autoserialize @autoserialize
qualifier: string; qualifier: string;
/** /**
* The scope note of this metadata field * The scope note of this metadata field
*/ */
@autoserialize @autoserialize
scopeNote: string; scopeNote: string;
/** /**
* The {@link HALLink}s for this MetadataField * The {@link HALLink}s for this MetadataField
*/ */
@deserialize @deserialize
_links: { _links: {
self: HALLink, self: HALLink,
schema: HALLink schema: HALLink
}; };
@@ -65,7 +65,7 @@ export class MetadataField extends ListableObject implements HALResource {
* Will be undefined unless the schema {@link HALLink} has been resolved. * Will be undefined unless the schema {@link HALLink} has been resolved.
*/ */
@link(METADATA_SCHEMA) @link(METADATA_SCHEMA)
schema?: Observable<RemoteData<MetadataSchema>>; schema?: Observable<RemoteData<MetadataSchema>>;
/** /**
* Method to print this metadata field as a string without the schema * Method to print this metadata field as a string without the schema

View File

@@ -19,29 +19,29 @@ export class MetadataSchema extends ListableObject implements HALResource {
* The unique identifier for this metadata schema * The unique identifier for this metadata schema
*/ */
@autoserialize @autoserialize
id: number; id: number;
/** /**
* The object type * The object type
*/ */
@excludeFromEquals @excludeFromEquals
@autoserialize @autoserialize
type: ResourceType; type: ResourceType;
/** /**
* A unique prefix that defines this schema * A unique prefix that defines this schema
*/ */
@autoserialize @autoserialize
prefix: string; prefix: string;
/** /**
* The namespace of this metadata schema * The namespace of this metadata schema
*/ */
@autoserialize @autoserialize
namespace: string; namespace: string;
@deserialize @deserialize
_links: { _links: {
self: HALLink, self: HALLink,
}; };

View File

@@ -308,11 +308,11 @@ export class MetadataService {
true, true,
followLink('primaryBitstream'), followLink('primaryBitstream'),
followLink('bitstreams', { followLink('bitstreams', {
findListOptions: { findListOptions: {
// limit the number of bitstreams used to find the citation pdf url to the number // limit the number of bitstreams used to find the citation pdf url to the number
// shown by default on an item page // shown by default on an item page
elementsPerPage: this.appConfig.item.bitstream.pageSize elementsPerPage: this.appConfig.item.bitstream.pageSize
} }
}, followLink('format')), }, followLink('format')),
).pipe( ).pipe(
getFirstSucceededRemoteDataPayload(), getFirstSucceededRemoteDataPayload(),

View File

@@ -19,49 +19,49 @@ export class OrcidHistory extends CacheableObject {
*/ */
@excludeFromEquals @excludeFromEquals
@autoserialize @autoserialize
type: ResourceType; type: ResourceType;
/** /**
* The identifier of this Orcid History record * The identifier of this Orcid History record
*/ */
@autoserialize @autoserialize
id: number; id: number;
/** /**
* The name of the related entity * The name of the related entity
*/ */
@autoserialize @autoserialize
entityName: string; entityName: string;
/** /**
* The identifier of the profileItem of this Orcid History record. * The identifier of the profileItem of this Orcid History record.
*/ */
@autoserialize @autoserialize
profileItemId: string; profileItemId: string;
/** /**
* The identifier of the entity related to this Orcid History record. * The identifier of the entity related to this Orcid History record.
*/ */
@autoserialize @autoserialize
entityId: string; entityId: string;
/** /**
* The type of the entity related to this Orcid History record. * The type of the entity related to this Orcid History record.
*/ */
@autoserialize @autoserialize
entityType: string; entityType: string;
/** /**
* The response status coming from ORCID api. * The response status coming from ORCID api.
*/ */
@autoserialize @autoserialize
status: number; status: number;
/** /**
* The putCode assigned by ORCID to the entity. * The putCode assigned by ORCID to the entity.
*/ */
@autoserialize @autoserialize
putCode: string; putCode: string;
/** /**
* The last send attempt timestamp. * The last send attempt timestamp.
@@ -82,7 +82,7 @@ export class OrcidHistory extends CacheableObject {
* The {@link HALLink}s for this Orcid History record * The {@link HALLink}s for this Orcid History record
*/ */
@deserialize @deserialize
_links: { _links: {
self: HALLink, self: HALLink,
}; };

View File

@@ -19,49 +19,49 @@ export class OrcidQueue extends CacheableObject {
*/ */
@excludeFromEquals @excludeFromEquals
@autoserialize @autoserialize
type: ResourceType; type: ResourceType;
/** /**
* The identifier of this Orcid Queue record * The identifier of this Orcid Queue record
*/ */
@autoserialize @autoserialize
id: number; id: number;
/** /**
* The record description. * The record description.
*/ */
@autoserialize @autoserialize
description: string; description: string;
/** /**
* The identifier of the profileItem of this Orcid Queue record. * The identifier of the profileItem of this Orcid Queue record.
*/ */
@autoserialize @autoserialize
profileItemId: string; profileItemId: string;
/** /**
* The identifier of the entity related to this Orcid Queue record. * The identifier of the entity related to this Orcid Queue record.
*/ */
@autoserialize @autoserialize
entityId: string; entityId: string;
/** /**
* The type of this Orcid Queue record. * The type of this Orcid Queue record.
*/ */
@autoserialize @autoserialize
recordType: string; recordType: string;
/** /**
* The operation related to this Orcid Queue record. * The operation related to this Orcid Queue record.
*/ */
@autoserialize @autoserialize
operation: string; operation: string;
/** /**
* The {@link HALLink}s for this Orcid Queue record * The {@link HALLink}s for this Orcid Queue record
*/ */
@deserialize @deserialize
_links: { _links: {
self: HALLink, self: HALLink,
}; };

Some files were not shown because too many files have changed in this diff Show More