Skip to content

Commit

Permalink
resources: add a config for resource context
Browse files Browse the repository at this point in the history
* Adds a configuration in routing data to set the context for the resource. This is useful for using resources in the context of `invenio-records-resources`.
* Uses `id` property of record instead of `metadata.pid` as this property not exists anymore with `invenio-records-resources`.
* Displays a default title for resource if `templateOptions.label` is not set.

Co-Authored-by: Sébastien Délèze <sebastien.deleze@rero.ch>
  • Loading branch information
Sébastien Délèze committed Mar 10, 2021
1 parent c6dcbf9 commit 40d5022
Show file tree
Hide file tree
Showing 14 changed files with 57 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export class SearchBarComponent implements OnInit {
query: '',
index: 'organisations',
category: this._translateService.instant('direct links'),
href: `/records/organisations/detail/${hit.metadata.pid}`,
href: `/records/organisations/detail/${hit.id}`,
iconCssClass: 'fa fa-bank'
});
});
Expand Down Expand Up @@ -136,7 +136,7 @@ export class SearchBarComponent implements OnInit {
query: hit.metadata.title.replace(/[:\-\[\]()/"]/g, ' ').replace(/\s\s+/g, ' '),
index: 'documents',
category: this._translateService.instant('documents')
// href: `/${this.viewcode}/documents/${hit.metadata.pid}`
// href: `/${this.viewcode}/documents/${hit.id}`
});
});
return values;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
'btn-outline-primary': !isPrimaryAction('edit'),
'btn-primary': isPrimaryAction('edit')
}"
[routerLink]="['../../edit', record.metadata.pid]"
[routerLink]="['../../edit', record.id]"
>
<i class="fa fa-pencil"></i>
{{ 'Edit' | translate }}
Expand All @@ -61,5 +61,5 @@
</ng-container>
</div>
<ng-template ngCoreRecordDetail></ng-template>
<ng-core-record-files [type]="type" [pid]="record.metadata.pid" *ngIf="record && filesEnabled"></ng-core-record-files>
<ng-core-record-files [type]="type" [pid]="record.id" *ngIf="record && filesEnabled"></ng-core-record-files>
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ export class DetailComponent implements OnInit, OnDestroy {
* @param element - string (PID to remove) or object
*/
deleteRecord(element: any) {
const pid = typeof element === 'object' ? element.metadata.pid : element;
const pid = typeof element === 'object' ? element.id : element;
return this._recordUiService.deleteRecord(this._type, pid).subscribe((result: any) => {
let redirectUrl = '../..';
const navigateOptions = { relativeTo: this._route };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { DetailRecord } from './detail-record';
@Component({
template: `
<ng-container *ngIf="record">
<h1>Record of type "{{ type }}" #{{ record.metadata.pid }}</h1>
<h1>Record of type "{{ type }}" #{{ record.id }}</h1>
{{ record|json }}
</ng-container>
`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
<div class="header py-2 mb-3 col-12 border-bottom">
<legend *ngIf="rootFomlyConfig">
<span [tooltip]="rootFomlyConfig.templateOptions.description">
{{ rootFomlyConfig.templateOptions.label }}
{{ rootFomlyConfig.templateOptions.label || recordType | ucfirst | translate }}
</span>
</legend>
<!-- buttons -->
Expand Down
25 changes: 19 additions & 6 deletions projects/rero/ng-core/src/lib/record/editor/editor.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,11 @@ export class EditorComponent implements OnInit, OnChanges, OnDestroy {
combineLatest([schema$, record$]).subscribe(
([schemaform, data]) => {
// Set schema
this.setSchema(schemaform.schema);
this.setSchema(
this._resourceConfig.recordResource
? schemaform.schema.properties.metadata
: schemaform.schema
);

// Check permissions and set record
if (data.result && data.result.can === false) {
Expand Down Expand Up @@ -322,6 +326,10 @@ export class EditorComponent implements OnInit, OnChanges, OnDestroy {
private _setModel(model: any): void {
if (this._resourceConfig != null) {
// the parent dont know that we are editing a record

// /!\ This will probably not work anymore with resources managed by
// invenio-records-resources, a fix will be necessary to make it work
// with both systems.
if (this.pid != null && (this.model == null || this.model.pid == null)) {
model.pid = this.pid;
}
Expand Down Expand Up @@ -462,9 +470,14 @@ export class EditorComponent implements OnInit, OnChanges, OnDestroy {
let data = removeEmptyValues(this.model);
data = this.postprocessRecord(data);

// For compatibility with resources managed with invenio-records-resources
if (this._resourceConfig.recordResource) {
data = { metadata: data };
}

let recordAction$: Observable<any>;
if (data.pid != null) {
recordAction$ = this._recordService.update(this.recordType, this.preUpdateRecord(data)).pipe(
if (this.pid != null) {
recordAction$ = this._recordService.update(this.recordType, this.pid, this.preUpdateRecord(data)).pipe(
catchError((error) => this._handleError(error)),
map(record => {
return { record, action: 'update', message: this._translateService.instant('Record updated.') };
Expand All @@ -485,7 +498,7 @@ export class EditorComponent implements OnInit, OnChanges, OnDestroy {
this._translateService.instant(this.recordType)
);
this._recordUiService.redirectAfterSave(
result.record.metadata.pid,
result.record.id,
result.record,
this.recordType,
result.action,
Expand Down Expand Up @@ -535,7 +548,7 @@ export class EditorComponent implements OnInit, OnChanges, OnDestroy {
component._translateService.instant(component.editorSettings.template.recordType)
);
component._recordUiService.redirectAfterSave(
createdRecord.metadata.pid,
createdRecord.id,
createdRecord,
component.editorSettings.template.recordType,
'create',
Expand Down Expand Up @@ -620,7 +633,7 @@ export class EditorComponent implements OnInit, OnChanges, OnDestroy {
: record.metadata.name,
value: this._apiService.getRefEndpoint(
recordType,
record.metadata.pid
record.id
)
};
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export class RemoteTypeaheadService {
results.hits.hits.map((hit: any) => {
names.push({
label: hit.metadata[options.label || options.field],
value: this._apiService.getRefEndpoint(options.type, hit.metadata.pid)
value: this._apiService.getRefEndpoint(options.type, hit.id)
// add a group field to group the results
// group: 'book'
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export class LoadTemplateFormComponent implements OnInit {
this._router.navigate([], {
queryParams: {
source: 'templates',
pid: template.metadata.pid
pid: template.id
},
queryParamsHandling: 'merge',
skipLocationChange: true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ export class RecordFilesComponent implements OnDestroy, OnInit {

// Update record
this._recordService
.update(this.type, this.record)
.update(this.type, this.pid, this.record)
.pipe(
switchMap(() => {
return this._getFiles$();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ describe('RecordService', () => {
};

service.getRecord('documents', '1').subscribe(data => {
expect(data.metadata.pid).toBe('1');
expect(data.id).toBe('1');
});

const req = httpMock.expectOne(request => {
Expand Down
36 changes: 20 additions & 16 deletions projects/rero/ng-core/src/lib/record/record.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import {
HttpClient,
HttpErrorResponse,
HttpHeaders,
HttpParams,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { TranslateService } from '@ngx-translate/core';
Expand Down Expand Up @@ -127,7 +132,7 @@ export class RecordService {
for (const key of Object.keys(preFilters)) {
const value = preFilters[key];
if (Array.isArray(value)) {
value.map(val => {
value.map((val) => {
httpParams = httpParams.append(key, val);
});
} else {
Expand Down Expand Up @@ -179,7 +184,7 @@ export class RecordService {
headers: this._createRequestHeaders(headers),
}
)
.pipe(catchError(error => this._handleError(error)));
.pipe(catchError((error) => this._handleError(error)));
}

/**
Expand Down Expand Up @@ -218,21 +223,18 @@ export class RecordService {
}

/**
* Create a new record
* Update a record
* @param recordType - string, type of resource
* @param record - object, record to create
* @param pid - string, record PID
* @param record - object, record to update
*/
update(recordType: string, record: { pid: string }) {
const url = `${this._apiService.getEndpointByType(recordType, true)}/${
record.pid
}`;
return this._http
.put(url, record)
.pipe(
catchError((error) => this._handleError(error)),
tap(() => this.onUpdate.next(this._createEvent(recordType, { record })))
);
update(recordType: string, pid: string, record: any) {
const url = `${this._apiService.getEndpointByType(recordType, true)}/${pid}`;

return this._http.put(url, record).pipe(
catchError((error) => this._handleError(error)),
tap(() => this.onUpdate.next(this._createEvent(recordType, { record })))
);
}

/**
Expand Down Expand Up @@ -317,7 +319,9 @@ export class RecordService {
switch (typeof total) {
case 'object':
if (relation) {
return `${this._translateService.instant(total.relation)} ${total.value.toString()}`;
return `${this._translateService.instant(
total.relation
)} ${total.value.toString()}`;
}
return Number(total.value);
case 'number':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -274,13 +274,13 @@ describe('RecordSearchComponent', () => {
component['currentType'] = 'documents';
component.detailUrl = '/custom/url/for/detail/:type/:pid';

component.resolveDetailUrl$({ metadata: { pid: 100 } }).subscribe((result: any) => {
component.resolveDetailUrl$({ id: 100 }).subscribe((result: any) => {
expect(result.link).toBe('/custom/url/for/detail/documents/100');
});

component.detailUrl = null;

component.resolveDetailUrl$({ metadata: { pid: 100 } }).subscribe((result: any) => {
component.resolveDetailUrl$({ id: 100 }).subscribe((result: any) => {
expect(result.link).toBe('detail/100');
});
}));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -658,10 +658,10 @@ export class RecordSearchComponent implements OnInit, OnChanges, OnDestroy {
* @return Observable emitting detail URL object
*/
resolveDetailUrl$(record: any): Observable<any> {
const url = { link: `detail/${record.metadata.pid}`, external: false };
const url = { link: `detail/${record.id}`, external: false };

if (this.detailUrl) {
url.link = this.detailUrl.replace(':type', this._currentIndex()).replace(':pid', record.metadata.pid);
url.link = this.detailUrl.replace(':type', this._currentIndex()).replace(':pid', record.id);
url.external = true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
class="btn btn-sm btn-outline-primary ml-2"
[title]="'Edit' | translate"
[name]="'Edit' | translate"
(click)="editRecord(record.metadata.pid)"
routerLink="edit/{{ record.metadata.pid }}">
(click)="editRecord(record.id)"
routerLink="edit/{{ record.id }}">
<i class="fa fa-pencil"></i>
</button>

Expand All @@ -44,7 +44,7 @@
class="btn btn-sm btn-outline-danger"
[title]="'Delete' | translate"
[name]="'Delete' | translate"
(click)="deleteRecord(record.metadata.pid)">
(click)="deleteRecord(record.id)">
<i class="fa fa-trash"></i>
</button>
<ng-template #deleteMessageLink>
Expand Down

0 comments on commit 40d5022

Please sign in to comment.