finalized put/patch requests

This commit is contained in:
lotte
2018-09-27 16:56:27 +02:00
parent dc5747982b
commit 1680f67744
14 changed files with 59 additions and 65 deletions

View File

@@ -33,6 +33,20 @@
[content]="collection.license" [content]="collection.license"
[title]="'collection.page.license'"> [title]="'collection.page.license'">
</ds-comcol-page-content> </ds-comcol-page-content>
<form (submit)="patchIt()">
<div class="row">
<div class="form-group col col-sm-4">
<label for="newname">Change Name</label>
<div class="input-group mb-3">
<input type="email" class="form-control" id="newname" name="newname"
placeholder="Enter a collection name" [(ngModel)]="newname">
<div class="input-group-append">
<button class="btn btn-danger" type="submit">Patch!</button>
</div>
</div>
</div>
</div>
</form>
</div> </div>
</div> </div>
<ds-error *ngIf="collectionRD?.hasFailed" message="{{'error.collection' | translate}}"></ds-error> <ds-error *ngIf="collectionRD?.hasFailed" message="{{'error.collection' | translate}}"></ds-error>

View File

@@ -15,7 +15,7 @@ import { Item } from '../core/shared/item.model';
import { fadeIn, fadeInOut } from '../shared/animations/fade'; import { fadeIn, fadeInOut } from '../shared/animations/fade';
import { hasValue, isNotEmpty } from '../shared/empty.util'; import { hasValue, isNotEmpty } from '../shared/empty.util';
import { PaginationComponentOptions } from '../shared/pagination/pagination-component-options.model'; import { PaginationComponentOptions } from '../shared/pagination/pagination-component-options.model';
import { filter, flatMap, map } from 'rxjs/operators'; import { filter, first, flatMap, map } from 'rxjs/operators';
import { SearchService } from '../+search-page/search-service/search.service'; import { SearchService } from '../+search-page/search-service/search.service';
import { PaginatedSearchOptions } from '../+search-page/paginated-search-options.model'; import { PaginatedSearchOptions } from '../+search-page/paginated-search-options.model';
import { toDSpaceObjectListRD } from '../core/shared/operators'; import { toDSpaceObjectListRD } from '../core/shared/operators';
@@ -39,6 +39,8 @@ export class CollectionPageComponent implements OnInit, OnDestroy {
sortConfig: SortOptions; sortConfig: SortOptions;
private subs: Subscription[] = []; private subs: Subscription[] = [];
private collectionId: string; private collectionId: string;
href: string;
newname: string;
constructor( constructor(
private collectionDataService: CollectionDataService, private collectionDataService: CollectionDataService,
@@ -77,6 +79,10 @@ export class CollectionPageComponent implements OnInit, OnDestroy {
}); });
}) })
); );
this.collectionRD$.pipe(first()).subscribe((crd) => {
this.href = crd.payload.self;
this.newname = crd.payload.name;
});
} }
updatePage(searchOptions) { updatePage(searchOptions) {
@@ -109,4 +115,9 @@ export class CollectionPageComponent implements OnInit, OnDestroy {
} }
}) })
} }
patchIt(): void {
console.log('patching it!', this.href, this.newname);
this.collectionDataService.patch(this.href, [{ op: 'replace', path: '/name', value: this.newname }]);
}
} }

View File

@@ -24,20 +24,6 @@
[content]="communityPayload.copyrightText" [content]="communityPayload.copyrightText"
[hasInnerHtml]="true"> [hasInnerHtml]="true">
</ds-comcol-page-content> </ds-comcol-page-content>
<form (submit)="patchIt()">
<div class="row">
<div class="form-group col col-sm-4">
<label for="newname">Change Name</label>
<div class="input-group mb-3">
<input type="email" class="form-control" id="newname" name="newname"
placeholder="Enter a collection name" [(ngModel)]="newname">
<div class="input-group-append">
<button class="btn btn-danger" type="submit">Patch!</button>
</div>
</div>
</div>
</div>
</form>
<ds-community-page-sub-collection-list <ds-community-page-sub-collection-list
[community]="communityPayload"></ds-community-page-sub-collection-list> [community]="communityPayload"></ds-community-page-sub-collection-list>
</div> </div>

View File

@@ -24,8 +24,7 @@ import { hasValue } from '../shared/empty.util';
export class CommunityPageComponent implements OnInit, OnDestroy { export class CommunityPageComponent implements OnInit, OnDestroy {
communityRD$: Observable<RemoteData<Community>>; communityRD$: Observable<RemoteData<Community>>;
logoRD$: Observable<RemoteData<Bitstream>>; logoRD$: Observable<RemoteData<Bitstream>>;
href: string;
newname: string;
private subs: Subscription[] = []; private subs: Subscription[] = [];
@@ -44,19 +43,13 @@ export class CommunityPageComponent implements OnInit, OnDestroy {
filter((community: Community) => hasValue(community)), filter((community: Community) => hasValue(community)),
mergeMap((community: Community) => community.logo)); mergeMap((community: Community) => community.logo));
this.communityRD$.pipe(first()).subscribe((crd) => {
this.href = crd.payload.self;
this.newname = crd.payload.name;
});
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.subs.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe()); this.subs.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe());
} }
patchIt(): void {
console.log('patching it!', this.href, this.newname);
this.communityDataService.patch(this.href, [{ op: 'replace', path: '/name', value: this.newname }]);
}
} }

View File

@@ -8,13 +8,13 @@ import { CoreState } from '../core.reducers';
import { AuthStatus } from './models/auth-status.model'; import { AuthStatus } from './models/auth-status.model';
import { AuthResponseParsingService } from './auth-response-parsing.service'; import { AuthResponseParsingService } from './auth-response-parsing.service';
import { AuthGetRequest, AuthPostRequest } from '../data/request.models'; import { AuthGetRequest, AuthPostRequest } from '../data/request.models';
import { getMockStore } from '../../shared/mocks/mock-store'; // import { getMockStore } from '../../shared/mocks/mock-store';
describe('AuthResponseParsingService', () => { describe('AuthResponseParsingService', () => {
let service: AuthResponseParsingService; let service: AuthResponseParsingService;
const EnvConfig = {cache: {msToLive: 1000}} as GlobalConfig; const EnvConfig = {cache: {msToLive: 1000}} as GlobalConfig;
const store = getMockStore() as Store<CoreState>; const store = {} as Store<CoreState>;
const objectCacheService = new ObjectCacheService(store); const objectCacheService = new ObjectCacheService(store);
beforeEach(() => { beforeEach(() => {

View File

@@ -17,7 +17,6 @@ import { REQUEST } from '@nguniversal/express-engine/tokens';
import { RouterReducerState } from '@ngrx/router-store'; import { RouterReducerState } from '@ngrx/router-store';
import { select, Store } from '@ngrx/store'; import { select, Store } from '@ngrx/store';
import { CookieAttributes } from 'js-cookie'; import { CookieAttributes } from 'js-cookie';
import { Observable } from 'rxjs/Observable';
import { EPerson } from '../eperson/models/eperson.model'; import { EPerson } from '../eperson/models/eperson.model';
import { AuthRequestService } from './auth-request.service'; import { AuthRequestService } from './auth-request.service';

View File

@@ -2,7 +2,7 @@ import { AuthError } from './auth-error.model';
import { AuthTokenInfo } from './auth-token-info.model'; import { AuthTokenInfo } from './auth-token-info.model';
import { EPerson } from '../../eperson/models/eperson.model'; import { EPerson } from '../../eperson/models/eperson.model';
import { RemoteData } from '../../data/remote-data'; import { RemoteData } from '../../data/remote-data';
import { Observable } from 'rxjs/Observable'; import { Observable } from 'rxjs/internal/Observable';
export class AuthStatus { export class AuthStatus {

View File

@@ -21,6 +21,7 @@ export interface Patch {
uuid?: string; uuid?: string;
operations: Operation[]; operations: Operation[];
} }
/**conca /**conca
* An interface to represent objects that can be cached * An interface to represent objects that can be cached
* *
@@ -119,7 +120,7 @@ function addToObjectCache(state: ObjectCacheState, action: AddToObjectCacheActio
timeAdded: action.payload.timeAdded, timeAdded: action.payload.timeAdded,
msToLive: action.payload.msToLive, msToLive: action.payload.msToLive,
requestHref: action.payload.requestHref, requestHref: action.payload.requestHref,
isDirty: false, isDirty: (hasValue(existing) ? isNotEmpty(existing.patches) : false),
patches: (hasValue(existing) ? existing.patches : []) patches: (hasValue(existing) ? existing.patches : [])
} }
}); });
@@ -206,9 +207,8 @@ function applyPatchObjectCache(state: ObjectCacheState, action: ApplyPatchObject
if (hasValue(newState[uuid])) { if (hasValue(newState[uuid])) {
// flatten two dimensional array // flatten two dimensional array
const flatPatch: Operation[] = [].concat(...newState[uuid].patches.map((patch) => patch.operations)); const flatPatch: Operation[] = [].concat(...newState[uuid].patches.map((patch) => patch.operations));
const newData = applyPatch( newState[uuid].data, flatPatch); const newData = applyPatch(newState[uuid].data, flatPatch, undefined, false);
newState[uuid].data = newData.newDocument; newState[uuid] = Object.assign({}, newState[uuid], { data: newData.newDocument, patches: [] });
newState[uuid].patches = [];
} }
return newState; return newState;
} }

View File

@@ -1,6 +1,6 @@
import { combineLatest as observableCombineLatest, Observable } from 'rxjs'; import { combineLatest as observableCombineLatest, Observable } from 'rxjs';
import { distinctUntilChanged, filter, first, map, mergeMap } from 'rxjs/operators'; import { distinctUntilChanged, filter, first, map, mergeMap, } from 'rxjs/operators';
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { MemoizedSelector, select, Store } from '@ngrx/store'; import { MemoizedSelector, select, Store } from '@ngrx/store';
import { IndexName } from '../index/index.reducer'; import { IndexName } from '../index/index.reducer';
@@ -18,9 +18,10 @@ import { coreSelector, CoreState } from '../core.reducers';
import { pathSelector } from '../shared/selectors'; import { pathSelector } from '../shared/selectors';
import { NormalizedObjectFactory } from './models/normalized-object-factory'; import { NormalizedObjectFactory } from './models/normalized-object-factory';
import { NormalizedObject } from './models/normalized-object.model'; import { NormalizedObject } from './models/normalized-object.model';
import { applyPatch, Operation } from 'fast-json-patch'; import { applyPatch, applyReducer, Operation } from 'fast-json-patch';
import { AddToSSBAction } from './server-sync-buffer.actions'; import { AddToSSBAction } from './server-sync-buffer.actions';
import { RestRequestMethod } from '../data/rest-request-method'; import { RestRequestMethod } from '../data/rest-request-method';
import { ReplaceOperation } from 'fast-json-patch/lib/core';
function selfLinkFromUuidSelector(uuid: string): MemoizedSelector<CoreState, string> { function selfLinkFromUuidSelector(uuid: string): MemoizedSelector<CoreState, string> {
return pathSelector<CoreState, string>(coreSelector, 'index', IndexName.OBJECT, uuid); return pathSelector<CoreState, string>(coreSelector, 'index', IndexName.OBJECT, uuid);
@@ -92,7 +93,7 @@ export class ObjectCacheService {
return this.getEntry(selfLink).pipe( return this.getEntry(selfLink).pipe(
map((entry: ObjectCacheEntry) => { map((entry: ObjectCacheEntry) => {
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).newDocument; const patchedData = applyPatch(entry.data, flatPatch, undefined, false).newDocument;
return Object.assign({}, entry, { data: patchedData }); return Object.assign({}, entry, { data: patchedData });
} }
), ),
@@ -114,7 +115,7 @@ export class ObjectCacheService {
getRequestHrefBySelfLink(selfLink: string): Observable<string> { getRequestHrefBySelfLink(selfLink: string): Observable<string> {
return this.getEntry(selfLink).pipe( return this.getEntry(selfLink).pipe(
map((entry: ObjectCacheEntry) => entry.requestHref), map((entry: ObjectCacheEntry) => entry.requestHref),
distinctUntilChanged(),); distinctUntilChanged());
} }
getRequestHrefByUUID(uuid: string): Observable<string> { getRequestHrefByUUID(uuid: string): Observable<string> {
@@ -211,7 +212,6 @@ export class ObjectCacheService {
} }
/** /**
* Add operations to the existing list of operations for an ObjectCacheEntry * Add operations to the existing list of operations for an ObjectCacheEntry
* Makes sure the ServerSyncBuffer for this ObjectCacheEntry is updated * Makes sure the ServerSyncBuffer for this ObjectCacheEntry is updated

View File

@@ -1,4 +1,4 @@
import { delay, exhaustMap, first, map, startWith, switchMap, tap } from 'rxjs/operators'; import { delay, exhaustMap, first, map, switchMap } from 'rxjs/operators';
import { Inject, Injectable } from '@angular/core'; import { Inject, Injectable } from '@angular/core';
import { Actions, Effect, ofType } from '@ngrx/effects'; import { Actions, Effect, ofType } from '@ngrx/effects';
import { import {
@@ -12,7 +12,7 @@ import { GlobalConfig } from '../../../config/global-config.interface';
import { coreSelector, CoreState } from '../core.reducers'; import { coreSelector, CoreState } from '../core.reducers';
import { Action, createSelector, MemoizedSelector, select, Store } from '@ngrx/store'; import { Action, createSelector, MemoizedSelector, select, Store } from '@ngrx/store';
import { ServerSyncBufferEntry, ServerSyncBufferState } from './server-sync-buffer.reducer'; import { ServerSyncBufferEntry, ServerSyncBufferState } from './server-sync-buffer.reducer';
import { of as observableOf, combineLatest as observableCombineLatest, empty as observableEmpty } from 'rxjs'; import { combineLatest as observableCombineLatest, of as observableOf } from 'rxjs';
import { RequestService } from '../data/request.service'; import { RequestService } from '../data/request.service';
import { PutRequest } from '../data/request.models'; import { PutRequest } from '../data/request.models';
import { ObjectCacheService } from './object-cache.service'; import { ObjectCacheService } from './object-cache.service';
@@ -41,7 +41,7 @@ export class ServerSyncBufferEffects {
switchMap((action: CommitSSBAction) => { switchMap((action: CommitSSBAction) => {
return this.store.pipe( return this.store.pipe(
select(serverSyncBufferSelector()), select(serverSyncBufferSelector()),
map((bufferState: ServerSyncBufferState) => { switchMap((bufferState: ServerSyncBufferState) => {
const actions: Array<Observable<Action>> = bufferState.buffer const actions: Array<Observable<Action>> = bufferState.buffer
.filter((entry: ServerSyncBufferEntry) => { .filter((entry: ServerSyncBufferEntry) => {
/* If there's a request method, filter /* If there's a request method, filter
@@ -53,41 +53,37 @@ export class ServerSyncBufferEffects {
}) })
.map((entry: ServerSyncBufferEntry) => { .map((entry: ServerSyncBufferEntry) => {
if (entry.method === RestRequestMethod.PATCH) { if (entry.method === RestRequestMethod.PATCH) {
console.log(this.applyPatch(entry.href));
return this.applyPatch(entry.href); return this.applyPatch(entry.href);
} else { } else {
/* TODO other request stuff */ /* TODO other request stuff */
} }
}); });
console.log(actions);
/* 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(
map((array) => { switchMap((array) => [...array, new EmptySSBAction(action.payload)])
console.log(array); );
return array.push(new EmptySSBAction(action.payload));
})
);
} else { } else {
return { type:'NO_ACTION' }; return observableOf({ type: 'NO_ACTION' });
} }
}) })
) )
}) })
); );
private applyPatch(href: string): Observable<Action> { private applyPatch(href: string): Observable<Action> {
const patchObject = this.objectCache.getBySelfLink(href); const patchObject = this.objectCache.getBySelfLink(href).pipe(first());
const test = patchObject.pipe(
return patchObject.pipe(
map((object) => { map((object) => {
const serializedObject = new DSpaceRESTv2Serializer(object.constructor as GenericConstructor<{}>).serialize(object); const serializedObject = new DSpaceRESTv2Serializer(object.constructor as GenericConstructor<{}>).serialize(object);
this.requestService.configure(new PutRequest(this.requestService.generateRequestId(), href, serializedObject)); this.requestService.configure(new PutRequest(this.requestService.generateRequestId(), href, serializedObject));
console.log(new ApplyPatchObjectCacheAction(href));
return new ApplyPatchObjectCacheAction(href) return new ApplyPatchObjectCacheAction(href)
}) })
) )
return test;
} }
constructor(private actions$: Actions, constructor(private actions$: Actions,

View File

@@ -1,11 +1,10 @@
import { Observable } from 'rxjs'; import { Observable, of as observableOf } from 'rxjs';
import { map, take } from 'rxjs/operators'; import { map } from 'rxjs/operators';
import { RemoteDataBuildService } from '../../core/cache/builders/remote-data-build.service'; import { RemoteDataBuildService } from '../../core/cache/builders/remote-data-build.service';
import { ResponseCacheEntry } from '../../core/cache/response-cache.reducer'; import { ResponseCacheEntry } from '../../core/cache/response-cache.reducer';
import { RemoteData } from '../../core/data/remote-data'; import { RemoteData } from '../../core/data/remote-data';
import { RequestEntry } from '../../core/data/request.reducer'; import { RequestEntry } from '../../core/data/request.reducer';
import { hasValue } from '../empty.util'; import { hasValue } from '../empty.util';
import { NormalizedObject } from '../../core/cache/models/normalized-object.model';
export function getMockRemoteDataBuildService(toRemoteDataObservable$?: Observable<RemoteData<any>>): RemoteDataBuildService { export function getMockRemoteDataBuildService(toRemoteDataObservable$?: Observable<RemoteData<any>>): RemoteDataBuildService {
return { return {
@@ -19,7 +18,7 @@ export function getMockRemoteDataBuildService(toRemoteDataObservable$?: Observab
} as RemoteData<any>))) } as RemoteData<any>)))
} }
}, },
buildSingle: (href$: string | Observable<string>) => Observable.of(new RemoteData(false, false, true, undefined, {})) buildSingle: (href$: string | Observable<string>) => observableOf(new RemoteData(false, false, true, undefined, {}))
} as RemoteDataBuildService; } as RemoteDataBuildService;
} }

View File

@@ -1,4 +0,0 @@
import { Store } from '@ngrx/store';
import { of as observableOf } from 'rxjs';

View File

@@ -52,6 +52,6 @@ export class RouteService {
}); });
return params; return params;
}), }),
distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),); distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)));
} }
} }

View File

@@ -27,7 +27,7 @@ export class AuthRequestServiceStub {
if (this.validateToken(token)) { if (this.validateToken(token)) {
authStatusStub.authenticated = true; authStatusStub.authenticated = true;
authStatusStub.token = this.mockTokenInfo; authStatusStub.token = this.mockTokenInfo;
authStatusStub.eperson = Observable.of(new RemoteData<EPerson>(false, false, true, undefined, this.mockUser)); authStatusStub.eperson = observableOf(new RemoteData<EPerson>(false, false, true, undefined, this.mockUser));
} else { } else {
authStatusStub.authenticated = false; authStatusStub.authenticated = false;
} }
@@ -46,7 +46,7 @@ export class AuthRequestServiceStub {
if (this.validateToken(token)) { if (this.validateToken(token)) {
authStatusStub.authenticated = true; authStatusStub.authenticated = true;
authStatusStub.token = this.mockTokenInfo; authStatusStub.token = this.mockTokenInfo;
authStatusStub.eperson = Observable.of(new RemoteData<EPerson>(false, false, true, undefined, this.mockUser)); authStatusStub.eperson = observableOf(new RemoteData<EPerson>(false, false, true, undefined, this.mockUser));
} else { } else {
authStatusStub.authenticated = false; authStatusStub.authenticated = false;
} }