mirror of
https://gitlab.com/openstapps/openstapps.git
synced 2026-01-19 08:02:55 +00:00
feat: add the app
This commit is contained in:
34
src/app/modules/data/data-routing.module.ts
Normal file
34
src/app/modules/data/data-routing.module.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {NgModule} from '@angular/core';
|
||||
import {RouterModule, Routes} from '@angular/router';
|
||||
import {DataDetailComponent} from './detail/data-detail.component';
|
||||
import {DataListComponent} from './list/data-list.component';
|
||||
|
||||
const dataRoutes: Routes = [
|
||||
{path: 'search', component: DataListComponent},
|
||||
{path: 'data-detail/:uid', component: DataDetailComponent}
|
||||
];
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
RouterModule.forChild(dataRoutes)
|
||||
],
|
||||
// tslint:disable-next-line:object-literal-sort-keys
|
||||
exports: [
|
||||
RouterModule
|
||||
]
|
||||
})
|
||||
export class DataRoutingModule {}
|
||||
18
src/app/modules/data/data.html
Normal file
18
src/app/modules/data/data.html
Normal file
@@ -0,0 +1,18 @@
|
||||
<!--
|
||||
Generated template for the DataPage page.
|
||||
|
||||
See http://ionicframework.com/docs/components/#navigation for more info on
|
||||
Ionic pages and navigation.
|
||||
-->
|
||||
<ion-header>
|
||||
|
||||
<ion-toolbar>
|
||||
<ion-title>data</ion-title>
|
||||
</ion-toolbar>
|
||||
|
||||
</ion-header>
|
||||
|
||||
|
||||
<ion-content padding>
|
||||
|
||||
</ion-content>
|
||||
56
src/app/modules/data/data.module.ts
Normal file
56
src/app/modules/data/data.module.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {HttpClientModule} from '@angular/common/http';
|
||||
import {NgModule} from '@angular/core';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {IonicModule} from '@ionic/angular';
|
||||
import {DataRoutingModule} from './data-routing.module';
|
||||
import {DataProvider, StAppsWebHttpClient} from './data.provider';
|
||||
import {DataDetailComponent} from './detail/data-detail.component';
|
||||
import {DataListItem} from './list/data-list-item.component';
|
||||
import {DataListComponent} from './list/data-list.component';
|
||||
import {DishDetailContentComponent} from './types/dish/dish-detail-content.component';
|
||||
import {DishListItem} from './types/dish/dish-list-item.component';
|
||||
import {EventListItemComponent} from './types/event/event-list-item.component';
|
||||
|
||||
@NgModule({
|
||||
declarations: [
|
||||
DataDetailComponent,
|
||||
|
||||
DishDetailContentComponent,
|
||||
DishListItem,
|
||||
|
||||
EventListItemComponent,
|
||||
|
||||
DataListItem,
|
||||
DataListComponent,
|
||||
],
|
||||
entryComponents: [
|
||||
DataListComponent,
|
||||
],
|
||||
imports: [
|
||||
IonicModule.forRoot(),
|
||||
CommonModule,
|
||||
FormsModule,
|
||||
DataRoutingModule,
|
||||
HttpClientModule,
|
||||
],
|
||||
providers: [
|
||||
DataProvider,
|
||||
StAppsWebHttpClient,
|
||||
],
|
||||
})
|
||||
export class DataModule {}
|
||||
81
src/app/modules/data/data.provider.ts
Normal file
81
src/app/modules/data/data.provider.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {HttpClient, HttpResponse} from '@angular/common/http';
|
||||
import {Injectable} from '@angular/core';
|
||||
import {HttpClientInterface, HttpClientRequest} from '@openstapps/api/lib/httpClientInterface';
|
||||
|
||||
/**
|
||||
* Response with generic for the type of body that is returned from the request
|
||||
*/
|
||||
export interface Response<TYPE_OF_BODY> extends HttpResponse<TYPE_OF_BODY> {
|
||||
body: TYPE_OF_BODY;
|
||||
statusCode: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* HttpClient that is based on angular's HttpClient (@TODO: move it to provider or independent package)
|
||||
*/
|
||||
@Injectable()
|
||||
export class StAppsWebHttpClient implements HttpClientInterface {
|
||||
constructor(private http: HttpClient) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a request
|
||||
* @param requestConfig Configuration of the request
|
||||
*/
|
||||
async request<TYPE_OF_BODY>(
|
||||
requestConfig: HttpClientRequest,
|
||||
): Promise<Response<TYPE_OF_BODY>> {
|
||||
const options: {
|
||||
[key: string]: any;
|
||||
observe: 'response';
|
||||
} = {
|
||||
body: {},
|
||||
observe: 'response',
|
||||
responseType: 'json',
|
||||
};
|
||||
|
||||
if (typeof requestConfig.body !== 'undefined') {
|
||||
options.body = requestConfig.body;
|
||||
}
|
||||
|
||||
if (typeof requestConfig.headers !== 'undefined') {
|
||||
options.headers = requestConfig.headers;
|
||||
}
|
||||
|
||||
try {
|
||||
const response: HttpResponse<TYPE_OF_BODY> = await this.http.request<TYPE_OF_BODY>(
|
||||
requestConfig.method || 'GET', requestConfig.url.toString(), options)
|
||||
.toPromise();
|
||||
return Object.assign(response, {statusCode: response.status, body: response.body || {}});
|
||||
} catch (err) {
|
||||
throw Error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Generated class for the DataProvider provider.
|
||||
|
||||
See https://angular.io/guide/dependency-injection for more info on providers
|
||||
and Angular DI.
|
||||
*/
|
||||
@Injectable()
|
||||
export class DataProvider {
|
||||
constructor() {
|
||||
// @TODO
|
||||
}
|
||||
}
|
||||
68
src/app/modules/data/detail/data-detail.component.spec.ts
Normal file
68
src/app/modules/data/detail/data-detail.component.spec.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
|
||||
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRoute, RouterModule} from '@angular/router';
|
||||
import {DataRoutingModule} from '../data-routing.module';
|
||||
import {DataListComponent} from '../list/data-list.component';
|
||||
import {DataDetailComponent} from './data-detail.component';
|
||||
|
||||
describe('DataDetailComponent', () => {
|
||||
let comp: DataDetailComponent;
|
||||
let fixture: ComponentFixture<DataDetailComponent>;
|
||||
let detailPage: HTMLElement;
|
||||
|
||||
// @Component({ selector: 'stapps-data-list-item', template: '' })
|
||||
// class DataListItemComponent {
|
||||
// @Input() item;
|
||||
// }
|
||||
|
||||
const fakeActivatedRoute = {
|
||||
snapshot: {
|
||||
paramMap: {
|
||||
get: (url) => {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
}
|
||||
} as ActivatedRoute;
|
||||
|
||||
beforeEach(async(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [DataListComponent, DataDetailComponent],
|
||||
imports: [RouterModule, DataRoutingModule],
|
||||
providers: [{provide: ActivatedRoute, useValue: fakeActivatedRoute}],
|
||||
schemas: [CUSTOM_ELEMENTS_SCHEMA],
|
||||
})
|
||||
.compileComponents();
|
||||
}));
|
||||
|
||||
beforeEach(async() => {
|
||||
fixture = await TestBed.createComponent(DataDetailComponent);
|
||||
comp = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create component', () =>
|
||||
expect(comp).toBeDefined(),
|
||||
);
|
||||
|
||||
it('should have apropriate title', () => {
|
||||
detailPage = fixture.nativeElement;
|
||||
const title: HTMLIonTitleElement | null = detailPage.querySelector('ion-title');
|
||||
expect(title).not.toBe(null);
|
||||
expect(title!.innerText).toContain('Detailansicht');
|
||||
});
|
||||
});
|
||||
41
src/app/modules/data/detail/data-detail.component.ts
Normal file
41
src/app/modules/data/detail/data-detail.component.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {Component} from '@angular/core';
|
||||
import {ActivatedRoute} from '@angular/router';
|
||||
import {SCThings} from '@openstapps/core';
|
||||
|
||||
@Component({
|
||||
selector: 'stapps-data-detail',
|
||||
templateUrl: 'data-detail.html'
|
||||
})
|
||||
export class DataDetailComponent {
|
||||
item: SCThings;
|
||||
constructor(private route: ActivatedRoute) {
|
||||
this.item = {
|
||||
categories: ['main dish'],
|
||||
name: 'Demo-Name',
|
||||
origin: {
|
||||
indexed: '2018-09-11T12:30:00Z',
|
||||
name: 'Dummy',
|
||||
},
|
||||
type: 'dish',
|
||||
uid: '',
|
||||
};
|
||||
}
|
||||
ngOnInit() {
|
||||
this.item.uid = this.route.snapshot.paramMap.get('uid') || '';
|
||||
this.item.description = 'Demo Beschreibung für das Item mit der UID ' + this.item.uid;
|
||||
}
|
||||
}
|
||||
21
src/app/modules/data/detail/data-detail.html
Normal file
21
src/app/modules/data/detail/data-detail.html
Normal file
@@ -0,0 +1,21 @@
|
||||
<ion-header>
|
||||
<ion-toolbar>
|
||||
<ion-buttons slot="start">
|
||||
<ion-back-button></ion-back-button>
|
||||
<ion-menu-button></ion-menu-button>
|
||||
</ion-buttons>
|
||||
<ion-title>Detailansicht</ion-title>
|
||||
</ion-toolbar>
|
||||
</ion-header>
|
||||
|
||||
<ion-content padding>
|
||||
<stapps-data-list-item [item]="item"></stapps-data-list-item>
|
||||
|
||||
<div [ngSwitch]="item.type">
|
||||
<stapps-dish-detail-content [item]="item" *ngSwitchCase="'dish'"></stapps-dish-detail-content>
|
||||
|
||||
<span *ngSwitchDefault>
|
||||
<p *ngIf="item.description">{{item.description}}</p>
|
||||
</span>
|
||||
</div>
|
||||
</ion-content>
|
||||
3
src/app/modules/data/detail/data-detail.scss
Normal file
3
src/app/modules/data/detail/data-detail.scss
Normal file
@@ -0,0 +1,3 @@
|
||||
stapps-data-detail {
|
||||
|
||||
}
|
||||
34
src/app/modules/data/list/data-list-item.component.ts
Normal file
34
src/app/modules/data/list/data-list-item.component.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {Component, Input, OnInit} from '@angular/core';
|
||||
import {SCThings} from '@openstapps/core';
|
||||
|
||||
@Component({
|
||||
selector: 'stapps-data-list-item',
|
||||
templateUrl: 'data-list-item.html'
|
||||
})
|
||||
export class DataListItem implements OnInit {
|
||||
@Input() item: SCThings;
|
||||
|
||||
constructor() {
|
||||
// noop
|
||||
// this.item is not available yet
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
// noop
|
||||
// this.item is available now - the template is loaded and compiled
|
||||
}
|
||||
}
|
||||
17
src/app/modules/data/list/data-list-item.html
Normal file
17
src/app/modules/data/list/data-list-item.html
Normal file
@@ -0,0 +1,17 @@
|
||||
<ion-item text-wrap button="true" lines="inset" [routerLink]="['/data-detail', item.uid]">
|
||||
<ion-thumbnail slot="start">
|
||||
<img src="../../../assets/imgs/logo.png">
|
||||
</ion-thumbnail>
|
||||
<ion-label [ngSwitch]="item.type" lines="full">
|
||||
<div>
|
||||
<stapps-dish-list-item [item]="item" *ngSwitchCase="'Dish'"></stapps-dish-list-item>
|
||||
|
||||
<stapps-event-list-item [item]="item" *ngSwitchCase="'Event'"></stapps-event-list-item>
|
||||
|
||||
<span *ngSwitchDefault>
|
||||
{{item.name}}<br/>
|
||||
<ion-note>{{item.type}}</ion-note>
|
||||
</span>
|
||||
</div>
|
||||
</ion-label>
|
||||
</ion-item>
|
||||
101
src/app/modules/data/list/data-list.component.ts
Normal file
101
src/app/modules/data/list/data-list.component.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {Component} from '@angular/core';
|
||||
import {AlertController, LoadingController} from '@ionic/angular';
|
||||
import {Client} from '@openstapps/api/lib/client';
|
||||
import {SCThing} from '@openstapps/core';
|
||||
import {Subject} from 'rxjs';
|
||||
import {debounceTime, distinctUntilChanged} from 'rxjs/operators';
|
||||
import {StAppsWebHttpClient} from '../data.provider';
|
||||
|
||||
@Component({
|
||||
selector: 'stapps-data-list',
|
||||
templateUrl: 'data-list.html',
|
||||
})
|
||||
export class DataListComponent {
|
||||
selectedItem: any;
|
||||
items: SCThing[] = [];
|
||||
|
||||
client: Client;
|
||||
|
||||
size: number = 30;
|
||||
from: number = 0;
|
||||
|
||||
query: string;
|
||||
queryChanged: Subject<string> = new Subject<string>();
|
||||
|
||||
loading: HTMLIonLoadingElement;
|
||||
|
||||
constructor(private loadingController: LoadingController,
|
||||
private alertController: AlertController,
|
||||
swHttpClient: StAppsWebHttpClient) {
|
||||
this.client = new Client(swHttpClient, 'https://stappsbe01.innocampus.tu-berlin.de', '1.0.6');
|
||||
|
||||
this.queryChanged
|
||||
.pipe(
|
||||
debounceTime(1000),
|
||||
distinctUntilChanged())
|
||||
.subscribe((model) => {
|
||||
this.from = 0;
|
||||
this.query = model;
|
||||
this.items = [];
|
||||
this.fetchItems();
|
||||
});
|
||||
|
||||
this.fetchItems();
|
||||
}
|
||||
|
||||
search(query: string) {
|
||||
this.queryChanged.next(query);
|
||||
}
|
||||
|
||||
async loadMore(event: any): Promise<any> {
|
||||
this.from += this.size;
|
||||
await this.fetchItems();
|
||||
event.target.complete();
|
||||
return;
|
||||
}
|
||||
|
||||
private async fetchItems(): Promise<any> {
|
||||
if (this.from === 0) {
|
||||
this.loading = await this.loadingController.create();
|
||||
await this.loading.present();
|
||||
}
|
||||
|
||||
return this.client.search({
|
||||
from: this.from,
|
||||
query: this.query,
|
||||
size: this.size
|
||||
} as any).then((result) => {
|
||||
result.data.forEach((item) => {
|
||||
this.items.push(item);
|
||||
});
|
||||
|
||||
if (this.from === 0) {
|
||||
this.loading.dismiss();
|
||||
}
|
||||
}, async (err) => {
|
||||
const alert: HTMLIonAlertElement = await this.alertController.create({
|
||||
buttons: ['Dismiss'],
|
||||
header: 'Error',
|
||||
subHeader: err.message,
|
||||
});
|
||||
|
||||
await alert.present();
|
||||
|
||||
await this.loading.dismiss();
|
||||
});
|
||||
}
|
||||
}
|
||||
22
src/app/modules/data/list/data-list.html
Normal file
22
src/app/modules/data/list/data-list.html
Normal file
@@ -0,0 +1,22 @@
|
||||
<ion-header>
|
||||
<ion-toolbar>
|
||||
<ion-buttons slot="start">
|
||||
<ion-back-button></ion-back-button>
|
||||
<ion-menu-button></ion-menu-button>
|
||||
</ion-buttons>
|
||||
|
||||
<ion-searchbar (ngModelChange)="search($event)" [(ngModel)]="query"></ion-searchbar>
|
||||
|
||||
<!--<ion-title>List</ion-title>-->
|
||||
</ion-toolbar>
|
||||
</ion-header>
|
||||
|
||||
<ion-content>
|
||||
<ion-list *ngFor="let item of items">
|
||||
<stapps-data-list-item [item]="item"></stapps-data-list-item>
|
||||
</ion-list>
|
||||
|
||||
<ion-infinite-scroll (ionInfinite)="loadMore($event)">
|
||||
<ion-infinite-scroll-content></ion-infinite-scroll-content>
|
||||
</ion-infinite-scroll>
|
||||
</ion-content>
|
||||
3
src/app/modules/data/list/data-list.scss
Normal file
3
src/app/modules/data/list/data-list.scss
Normal file
@@ -0,0 +1,3 @@
|
||||
stapps-data-list {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {Component, Input} from '@angular/core';
|
||||
import {LangChangeEvent, TranslateService} from '@ngx-translate/core';
|
||||
import {SCDish, SCDishMeta, SCLanguageName, SCThingMeta} from '@openstapps/core';
|
||||
|
||||
@Component({
|
||||
selector: 'stapps-dish-detail-content',
|
||||
templateUrl: 'dish-detail-content.html'
|
||||
})
|
||||
export class DishDetailContentComponent {
|
||||
@Input() item: SCDish;
|
||||
language: SCLanguageName;
|
||||
meta: SCThingMeta;
|
||||
|
||||
constructor(translateService: TranslateService) {
|
||||
this.language = translateService.currentLang as SCLanguageName;
|
||||
|
||||
this.meta = SCDishMeta;
|
||||
|
||||
translateService.onLangChange.subscribe((event: LangChangeEvent) => {
|
||||
this.language = event.lang as SCLanguageName;
|
||||
});
|
||||
}
|
||||
}
|
||||
47
src/app/modules/data/types/dish/dish-detail-content.html
Normal file
47
src/app/modules/data/types/dish/dish-detail-content.html
Normal file
@@ -0,0 +1,47 @@
|
||||
<ion-card *ngIf="item.description">
|
||||
<ion-card-header>{{meta.getFieldTranslation(language, 'description')}}</ion-card-header>
|
||||
<ion-card-content>{{item.description}}</ion-card-content>
|
||||
</ion-card>
|
||||
|
||||
<ion-card *ngIf="item.categories">
|
||||
<ion-card-header>{{meta.getFieldTranslation(language, 'categories')}}</ion-card-header>
|
||||
<ion-card-content>{{item.categories.join(', ')}}</ion-card-content>
|
||||
</ion-card>
|
||||
|
||||
<ion-card *ngIf="item.characteristics">
|
||||
<ion-card-header>{{meta.getFieldTranslation(language, 'characteristics')}}</ion-card-header>
|
||||
<ion-card-content>{{item.characteristics.join(', ')}}</ion-card-content>
|
||||
</ion-card>
|
||||
|
||||
<ion-card *ngIf="item.additives">
|
||||
<ion-card-header>{{meta.getFieldTranslation(language, 'additives')}}</ion-card-header>
|
||||
<ion-card-content>{{item.additives.join(', ')}}</ion-card-content>
|
||||
</ion-card>
|
||||
|
||||
<ion-card *ngIf="item.place">
|
||||
<ion-card-header>{{meta.getFieldTranslation(language, 'place')}}</ion-card-header>
|
||||
<ion-card-content><a>{{item.place.name}}</a></ion-card-content>
|
||||
</ion-card>
|
||||
|
||||
<ion-card>
|
||||
<ion-card-header>{{meta.getFieldTranslation(language, 'price')}}</ion-card-header>
|
||||
<ion-card-content>
|
||||
<ion-grid>
|
||||
<ion-row *ngFor="let offer of item.offers">
|
||||
<ion-col>
|
||||
{{offer.universityRole.name}}
|
||||
</ion-col>
|
||||
<ion-col>{{offer.price}}</ion-col>
|
||||
</ion-row>
|
||||
<ion-row>
|
||||
<ion-col>Standard / Gäste</ion-col>
|
||||
<ion-col>{{item.price}}</ion-col>
|
||||
</ion-row>
|
||||
</ion-grid>
|
||||
</ion-card-content>
|
||||
</ion-card>
|
||||
|
||||
<ion-card *ngIf="item.availabilityStarts">
|
||||
<ion-card-header>Verfügbarkeit</ion-card-header>
|
||||
<ion-card-content>{{item.availabilityStarts | date}}</ion-card-content>
|
||||
</ion-card>
|
||||
25
src/app/modules/data/types/dish/dish-list-item.component.ts
Normal file
25
src/app/modules/data/types/dish/dish-list-item.component.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {Component, Input} from '@angular/core';
|
||||
import {SCDish} from '@openstapps/core';
|
||||
import {DataListItem} from '../../list/data-list-item.component';
|
||||
|
||||
@Component({
|
||||
selector: 'stapps-dish-list-item',
|
||||
templateUrl: 'dish-list-item.html',
|
||||
})
|
||||
export class DishListItem extends DataListItem {
|
||||
@Input() item: SCDish;
|
||||
}
|
||||
6
src/app/modules/data/types/dish/dish-list-item.html
Normal file
6
src/app/modules/data/types/dish/dish-list-item.html
Normal file
@@ -0,0 +1,6 @@
|
||||
{{item.name}}<br/>
|
||||
<ion-note>
|
||||
{{item.price}}
|
||||
{{item.categories.join(',')}}
|
||||
{{item.place.name}}
|
||||
</ion-note>
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {Component, Input} from '@angular/core';
|
||||
import {SCDateSeries} from '@openstapps/core';
|
||||
import {DataListItem} from '../../list/data-list-item.component';
|
||||
|
||||
@Component({
|
||||
selector: 'stapps-event-list-item',
|
||||
templateUrl: 'event-list-item.html'
|
||||
})
|
||||
export class EventListItemComponent extends DataListItem {
|
||||
@Input() item: SCDateSeries;
|
||||
}
|
||||
7
src/app/modules/data/types/event/event-list-item.html
Normal file
7
src/app/modules/data/types/event/event-list-item.html
Normal file
@@ -0,0 +1,7 @@
|
||||
{{item.name}}<br/>
|
||||
|
||||
<ion-note>
|
||||
{{item.subProperties.semester}}
|
||||
{{item.categories.join(', ')}}
|
||||
{{item.startDate}} - {{item.endDate}}
|
||||
</ion-note>
|
||||
37
src/app/modules/menu/menu.module.ts
Normal file
37
src/app/modules/menu/menu.module.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {NgModule} from '@angular/core';
|
||||
import {RouterModule} from '@angular/router';
|
||||
import {IonicModule} from '@ionic/angular';
|
||||
import {NavigationComponent} from './navigation/navigation.component';
|
||||
|
||||
@NgModule({
|
||||
declarations: [
|
||||
NavigationComponent,
|
||||
],
|
||||
entryComponents: [
|
||||
NavigationComponent
|
||||
],
|
||||
exports: [
|
||||
NavigationComponent
|
||||
],
|
||||
imports: [
|
||||
IonicModule.forRoot(),
|
||||
CommonModule,
|
||||
RouterModule
|
||||
]
|
||||
})
|
||||
export class MenuModule {}
|
||||
45
src/app/modules/menu/navigation/navigation.component.ts
Normal file
45
src/app/modules/menu/navigation/navigation.component.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {Component} from '@angular/core';
|
||||
|
||||
/**
|
||||
* Generated class for the MenuPage page.
|
||||
*
|
||||
* See https://ionicframework.com/docs/components/#navigation for more info on
|
||||
* Ionic pages and navigation.
|
||||
*/
|
||||
|
||||
@Component({
|
||||
selector: 'stapps-navigation',
|
||||
templateUrl: 'navigation.html',
|
||||
})
|
||||
export class NavigationComponent {
|
||||
public pages = [
|
||||
{title: 'Search', url: '/search', icon: 'search'},
|
||||
{title: 'Settings', url: '/settings', icon: 'settings'},
|
||||
];
|
||||
|
||||
constructor() {
|
||||
// Nothing yet.
|
||||
}
|
||||
|
||||
ionViewDidLoad() {
|
||||
// console.log('ionViewDidLoad MenuPage');
|
||||
}
|
||||
|
||||
// openPage(page) {
|
||||
// this.nav.setRoot(page.component);
|
||||
// }
|
||||
}
|
||||
25
src/app/modules/menu/navigation/navigation.html
Normal file
25
src/app/modules/menu/navigation/navigation.html
Normal file
@@ -0,0 +1,25 @@
|
||||
<ion-split-pane>
|
||||
<ion-menu>
|
||||
<ion-header>
|
||||
<ion-toolbar>
|
||||
<ion-buttons slot="start">
|
||||
<ion-back-button></ion-back-button>
|
||||
</ion-buttons>
|
||||
<ion-title>StApps</ion-title>
|
||||
</ion-toolbar>
|
||||
</ion-header>
|
||||
<ion-content>
|
||||
<ion-list>
|
||||
<ion-menu-toggle auto-hide="false" *ngFor="let p of pages">
|
||||
<ion-item [routerDirection]="'root'" [routerLink]="[p.url]">
|
||||
<ion-icon slot="start" [name]="p.icon"></ion-icon>
|
||||
<ion-label>
|
||||
{{p.title}}
|
||||
</ion-label>
|
||||
</ion-item>
|
||||
</ion-menu-toggle>
|
||||
</ion-list>
|
||||
</ion-content>
|
||||
</ion-menu>
|
||||
<ion-router-outlet main></ion-router-outlet>
|
||||
</ion-split-pane>
|
||||
3
src/app/modules/menu/navigation/navigation.scss
Normal file
3
src/app/modules/menu/navigation/navigation.scss
Normal file
@@ -0,0 +1,3 @@
|
||||
stapps-navigation {
|
||||
|
||||
}
|
||||
68
src/app/modules/settings/item/settings-item.component.ts
Normal file
68
src/app/modules/settings/item/settings-item.component.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {Component, Input} from '@angular/core';
|
||||
import {LangChangeEvent, TranslateService} from '@ngx-translate/core';
|
||||
import {
|
||||
SCLanguageName,
|
||||
SCSetting,
|
||||
SCSettingMeta,
|
||||
} from '@openstapps/core';
|
||||
import {SettingsProvider} from '../../settingsProvider/settings.provider';
|
||||
|
||||
@Component({
|
||||
selector: 'stapps-settings-item',
|
||||
templateUrl: 'settings-item.html',
|
||||
})
|
||||
export class SettingsItemComponent {
|
||||
isVisible = true;
|
||||
language: SCLanguageName;
|
||||
meta = SCSettingMeta;
|
||||
|
||||
@Input() setting: SCSetting;
|
||||
|
||||
constructor(private translateService: TranslateService,
|
||||
private settingsProvider: SettingsProvider) {
|
||||
this.meta = SCSettingMeta;
|
||||
|
||||
this.language = translateService.currentLang as SCLanguageName;
|
||||
|
||||
translateService.onLangChange.subscribe((event: LangChangeEvent) => {
|
||||
this.isVisible = false;
|
||||
this.language = event.lang as SCLanguageName;
|
||||
// workaround for selected 'select option' not updating translation
|
||||
setTimeout(() => this.isVisible = true);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* handles value changes of the setting
|
||||
*/
|
||||
async settingChanged(): Promise<void> {
|
||||
switch (this.setting.name) {
|
||||
case 'language':
|
||||
if (this.setting.input.value !== undefined) {
|
||||
this.translateService.use(this.setting.input.value.toString());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
}
|
||||
await this.settingsProvider
|
||||
.setSettingValue(this.setting.categories[0], this.setting.name, this.setting.input.value);
|
||||
}
|
||||
|
||||
typeOf(val: any) {
|
||||
return typeof (val);
|
||||
}
|
||||
}
|
||||
55
src/app/modules/settings/item/settings-item.html
Normal file
55
src/app/modules/settings/item/settings-item.html
Normal file
@@ -0,0 +1,55 @@
|
||||
<ion-card>
|
||||
<ion-card-header>
|
||||
<span id="settingTitle" >{{ meta.getFieldValueTranslation(language, 'name', setting) }}</span>
|
||||
</ion-card-header>
|
||||
<ion-card-content>
|
||||
<ion-note >{{ meta.getFieldValueTranslation(language, 'description', setting) }}</ion-note>
|
||||
|
||||
<div [ngSwitch]="setting.input.inputType" *ngIf="isVisible" >
|
||||
<ion-item *ngSwitchCase="'toggle'">
|
||||
<ion-label></ion-label>
|
||||
<ion-toggle start [(ngModel)]="setting.input.value" (ionChange)="settingChanged()"></ion-toggle>
|
||||
</ion-item>
|
||||
<ion-item *ngSwitchCase="'number'">
|
||||
<ion-label></ion-label>
|
||||
<ion-input type='number' [(ngModel)]="setting.input.value" value={{setting.input.value}} (ionChange)="settingChanged()"></ion-input>
|
||||
</ion-item>
|
||||
|
||||
<ion-item *ngSwitchCase="'text'">
|
||||
<ion-label></ion-label>
|
||||
<ion-input type="text" [(ngModel)]="setting.input.value" value={{setting.input.value}} (ionChange)="settingChanged()"></ion-input>
|
||||
</ion-item>
|
||||
|
||||
<ion-item *ngSwitchCase="'password'">
|
||||
<ion-label></ion-label>
|
||||
<ion-input type="password" [(ngModel)]="setting.input.value" value={{setting.input.value}} (ionChange)="settingChanged()"></ion-input>
|
||||
</ion-item>
|
||||
|
||||
<ion-item *ngSwitchCase="'singleChoice'">
|
||||
<ion-label></ion-label>
|
||||
<ion-toggle *ngIf="typeOf(setting.input.defaultValue) === 'boolean'" [(ngModel)]="setting.input.value" (ionChange)="settingChanged()"></ion-toggle>
|
||||
<ion-select *ngIf="typeOf(setting.input.defaultValue) !== 'boolean'" interface="popover" [(ngModel)]="setting.input.value" (ionChange)="settingChanged()">
|
||||
<ion-select-option *ngFor="let val of setting.input.values" [value]="val">
|
||||
<div *ngIf="typeOf(val) !== 'number'">{{ val }}</div>
|
||||
<div *ngIf="typeOf(val) === 'number'">{{ val }}</div>
|
||||
</ion-select-option>
|
||||
</ion-select>
|
||||
</ion-item>
|
||||
|
||||
<ion-item *ngSwitchCase="'multipleChoice'">
|
||||
<ion-label></ion-label>
|
||||
<ion-select [(ngModel)]="setting.input.value" multiple="true" (ionChange)="settingChanged()">
|
||||
<ion-select-option *ngFor="let val of setting.input.values" [value]="val">
|
||||
<div *ngIf="typeOf(val) !== 'number'">{{ val }}</div>
|
||||
<div *ngIf="typeOf(val) === 'number'">{{ val }}</div>
|
||||
</ion-select-option>
|
||||
</ion-select>
|
||||
</ion-item>
|
||||
|
||||
<span *ngSwitchDefault>
|
||||
<ion-note>no template for {{ setting.name }}</ion-note>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
</ion-card-content>
|
||||
</ion-card>
|
||||
48
src/app/modules/settings/page/settings-page.component.ts
Normal file
48
src/app/modules/settings/page/settings-page.component.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {Component, OnInit} from '@angular/core';
|
||||
import {LangChangeEvent, TranslateService} from '@ngx-translate/core';
|
||||
import {SCLanguageName, SCSettingMeta} from '@openstapps/core';
|
||||
import {SettingsCache, SettingsProvider} from '../../settingsProvider/settings.provider';
|
||||
|
||||
@Component({
|
||||
selector: 'stapps-settings-page',
|
||||
templateUrl: 'settings-page.html',
|
||||
})
|
||||
export class SettingsPageComponent implements OnInit {
|
||||
categoriesOrder: string[];
|
||||
language: SCLanguageName;
|
||||
meta = SCSettingMeta;
|
||||
objectKeys = Object.keys;
|
||||
settingsCache: SettingsCache;
|
||||
|
||||
constructor(public settingsProvider: SettingsProvider,
|
||||
translateService: TranslateService) {
|
||||
this.language = translateService.currentLang as SCLanguageName;
|
||||
translateService.onLangChange.subscribe((event: LangChangeEvent) => {
|
||||
this.language = event.lang as SCLanguageName;
|
||||
});
|
||||
this.settingsCache = {};
|
||||
this.categoriesOrder = settingsProvider.getCategoriesOrder();
|
||||
}
|
||||
|
||||
async loadSettings(): Promise<void> {
|
||||
this.settingsCache = await this.settingsProvider.getSettingsCache();
|
||||
}
|
||||
|
||||
async ngOnInit() {
|
||||
await this.loadSettings();
|
||||
}
|
||||
}
|
||||
20
src/app/modules/settings/page/settings-page.html
Normal file
20
src/app/modules/settings/page/settings-page.html
Normal file
@@ -0,0 +1,20 @@
|
||||
|
||||
<ion-header>
|
||||
<ion-toolbar>
|
||||
<ion-buttons slot="start">
|
||||
<ion-back-button></ion-back-button>
|
||||
<ion-menu-button></ion-menu-button>
|
||||
</ion-buttons>
|
||||
<ion-title ><div id="title" > {{'settings.title' | translate}}</div></ion-title>
|
||||
</ion-toolbar>
|
||||
</ion-header>
|
||||
|
||||
<ion-content >
|
||||
<ion-list *ngFor="let categoryKey of categoriesOrder ">
|
||||
<div *ngIf="objectKeys(settingsCache).includes(categoryKey)">
|
||||
<ion-item-divider><h5>{{ meta.getFieldValueTranslation(language, 'categories',
|
||||
settingsCache[categoryKey].settings[objectKeys(settingsCache[categoryKey].settings)[0]]) }}</h5></ion-item-divider>
|
||||
<stapps-settings-item *ngFor="let settingKeys of objectKeys(settingsCache[categoryKey].settings)" [setting]="settingsCache[categoryKey].settings[settingKeys]"></stapps-settings-item>
|
||||
</div>
|
||||
</ion-list>
|
||||
</ion-content>
|
||||
44
src/app/modules/settings/settings.module.ts
Normal file
44
src/app/modules/settings/settings.module.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {NgModule} from '@angular/core';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {RouterModule, Routes} from '@angular/router';
|
||||
import {IonicModule} from '@ionic/angular';
|
||||
import {TranslateModule} from '@ngx-translate/core';
|
||||
|
||||
import {SettingsItemComponent} from './item/settings-item.component';
|
||||
import {SettingsPageComponent} from './page/settings-page.component';
|
||||
|
||||
const settingsRoutes: Routes = [
|
||||
{ path: 'settings', component: SettingsPageComponent },
|
||||
];
|
||||
|
||||
@NgModule({
|
||||
declarations: [
|
||||
SettingsPageComponent,
|
||||
SettingsItemComponent,
|
||||
],
|
||||
imports: [
|
||||
CommonModule,
|
||||
FormsModule,
|
||||
IonicModule.forRoot(),
|
||||
TranslateModule.forChild(),
|
||||
RouterModule.forChild(settingsRoutes),
|
||||
],
|
||||
providers: [
|
||||
],
|
||||
})
|
||||
export class SettingsModule {}
|
||||
3
src/app/modules/settings/settings.scss
Normal file
3
src/app/modules/settings/settings.scss
Normal file
@@ -0,0 +1,3 @@
|
||||
page-settings {
|
||||
|
||||
}
|
||||
349
src/app/modules/settingsProvider/settings.provider.spec.ts
Normal file
349
src/app/modules/settingsProvider/settings.provider.spec.ts
Normal file
@@ -0,0 +1,349 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {SCSetting} from '@openstapps/core';
|
||||
import {StorageModule} from '../storage/storage.module';
|
||||
import {StorageProvider} from '../storage/storage.provider';
|
||||
import {SettingsProvider} from './settings.provider';
|
||||
|
||||
describe('SettingsProvider', () => {
|
||||
let settingsProvider: SettingsProvider;
|
||||
let storageModule: StorageProvider;
|
||||
|
||||
beforeEach(async () => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [StorageModule],
|
||||
providers: [SettingsProvider, StorageProvider],
|
||||
});
|
||||
settingsProvider = TestBed.get(SettingsProvider);
|
||||
storageModule = TestBed.get(StorageProvider);
|
||||
|
||||
settingsProvider.clear();
|
||||
});
|
||||
|
||||
it('should provide and get setting', async () => {
|
||||
await settingsProvider.provideSetting(JSON.parse(JSON.stringify(SETTING_MOCKS[0])));
|
||||
const setting = await settingsProvider.getSetting(SETTING_MOCKS[0].categories[0], SETTING_MOCKS[0].name);
|
||||
await expect(setting).toBeDefined();
|
||||
});
|
||||
|
||||
it('should provide and get settings value', async () => {
|
||||
await settingsProvider.provideSetting(JSON.parse(JSON.stringify(SETTING_MOCKS[0])));
|
||||
const value = await settingsProvider.getSettingValue(SETTING_MOCKS[0].categories[0], SETTING_MOCKS[0].name);
|
||||
await expect(value).toBeDefined();
|
||||
});
|
||||
|
||||
it('should set value of a provided setting', async () => {
|
||||
await settingsProvider.provideSetting(JSON.parse(JSON.stringify(SETTING_MOCKS[0])));
|
||||
await settingsProvider.setSettingValue(SETTING_MOCKS[0].categories[0], SETTING_MOCKS[0].name, 'updated');
|
||||
const value = await settingsProvider.getSettingValue(SETTING_MOCKS[0].categories[0], SETTING_MOCKS[0].name);
|
||||
await expect(value).toEqual('updated');
|
||||
});
|
||||
|
||||
it('should return copy of settingsCache', async () => {
|
||||
const category = SETTING_MOCKS[0].categories[0];
|
||||
const name = SETTING_MOCKS[0].name;
|
||||
await settingsProvider.provideSetting(JSON.parse(JSON.stringify(SETTING_MOCKS[0])));
|
||||
const settings = await settingsProvider.getSettingsCache();
|
||||
settings[category].settings[name].input.value = 'testValue';
|
||||
// cached setting value should still be defaultValue
|
||||
await expect((await settingsProvider.getSettingValue(category, name)))
|
||||
.toEqual(SETTING_MOCKS[0].input.defaultValue);
|
||||
});
|
||||
|
||||
it('should call storage put on provideSetting', async () => {
|
||||
spyOn(storageModule, 'put');
|
||||
await settingsProvider.provideSetting(JSON.parse(JSON.stringify(SETTING_MOCKS[0])));
|
||||
await expect(storageModule.put).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should call storage put on setSettingValue', async () => {
|
||||
await settingsProvider.provideSetting(JSON.parse(JSON.stringify(SETTING_MOCKS[0])));
|
||||
spyOn(storageModule, 'put');
|
||||
await settingsProvider.setSettingValue(SETTING_MOCKS[0].categories[0], SETTING_MOCKS[0].name, '');
|
||||
await expect(storageModule.put).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should clear settings', async () => {
|
||||
const category = SETTING_MOCKS[0].categories[0];
|
||||
const name = SETTING_MOCKS[0].name;
|
||||
await settingsProvider.provideSetting(JSON.parse(JSON.stringify(SETTING_MOCKS[0])));
|
||||
await settingsProvider.clear();
|
||||
const exists = await settingsProvider.settingExists(category, name);
|
||||
await expect(exists).toEqual(false);
|
||||
});
|
||||
|
||||
it('should reset settings', async () => {
|
||||
const category = SETTING_MOCKS[0].categories[0];
|
||||
const name = SETTING_MOCKS[0].name;
|
||||
await settingsProvider.provideSetting(JSON.parse(JSON.stringify(SETTING_MOCKS[0])));
|
||||
await settingsProvider.setSettingValue(category, name, 'guest');
|
||||
await settingsProvider.resetDefault();
|
||||
const value = await settingsProvider.getSettingValue(SETTING_MOCKS[0].categories[0], SETTING_MOCKS[0].name);
|
||||
await expect(value).toEqual(SETTING_MOCKS[0].input.defaultValue);
|
||||
});
|
||||
|
||||
it('should validate wrong values for inputType text', async () => {
|
||||
await testValue(SETTING_MOCKS[0], 123456789);
|
||||
await testValue(SETTING_MOCKS[0], false);
|
||||
await testValue(SETTING_MOCKS[0], []);
|
||||
});
|
||||
|
||||
it('should validate wrong values for inputType password', async () => {
|
||||
await testValue(SETTING_MOCKS[0], 123456789);
|
||||
await testValue(SETTING_MOCKS[0], false);
|
||||
await testValue(SETTING_MOCKS[0], []);
|
||||
});
|
||||
|
||||
it('should validate wrong values for inputType number', async () => {
|
||||
await testValue(SETTING_MOCKS[2], '');
|
||||
await testValue(SETTING_MOCKS[2], false);
|
||||
await testValue(SETTING_MOCKS[2], []);
|
||||
});
|
||||
|
||||
it('should validate wrong values for inputType singleChoice text', async () => {
|
||||
await testValue(SETTING_MOCKS[3], '');
|
||||
await testValue(SETTING_MOCKS[3], 123456);
|
||||
await testValue(SETTING_MOCKS[3], false);
|
||||
await testValue(SETTING_MOCKS[3], []);
|
||||
});
|
||||
|
||||
it('should validate wrong values for inputType singleChoice boolean', async () => {
|
||||
await testValue(SETTING_MOCKS[5], '');
|
||||
await testValue(SETTING_MOCKS[5], 123456);
|
||||
await testValue(SETTING_MOCKS[5], []);
|
||||
});
|
||||
|
||||
it('should validate wrong values for inputType multipleChoice', async () => {
|
||||
await testValue(SETTING_MOCKS[6], '');
|
||||
await testValue(SETTING_MOCKS[6], 123456);
|
||||
await testValue(SETTING_MOCKS[6], false);
|
||||
await testValue(SETTING_MOCKS[6], [1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
async function testValue(setting: SCSetting, value: any) {
|
||||
let error: Error;
|
||||
await settingsProvider.provideSetting(JSON.parse(JSON.stringify(setting)));
|
||||
try {
|
||||
await settingsProvider.setSettingValue(setting.categories[0], setting.name, value);
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
// @ts-ignore
|
||||
await expect(error).toBeDefined();
|
||||
// @ts-ignore
|
||||
await expect(error.message).toMatch(/Value.*not valid/);
|
||||
}
|
||||
|
||||
const SETTING_MOCKS: SCSetting[] = [
|
||||
{
|
||||
categories: ['credentials'],
|
||||
input: {
|
||||
defaultValue: '',
|
||||
inputType: 'text',
|
||||
},
|
||||
name: 'username',
|
||||
order: 0,
|
||||
origin: {
|
||||
indexed: '2018-09-11T12:30:00Z',
|
||||
name: 'Dummy',
|
||||
},
|
||||
translations: {
|
||||
de: {
|
||||
categories: ['Anmeldedaten'],
|
||||
name: 'Benutzername',
|
||||
},
|
||||
en: {
|
||||
categories: ['Credentials'],
|
||||
name: 'Username',
|
||||
},
|
||||
},
|
||||
type: 'setting',
|
||||
uid: '',
|
||||
},
|
||||
{
|
||||
categories: ['credentials'],
|
||||
description: '',
|
||||
input: {
|
||||
defaultValue: '',
|
||||
inputType: 'password',
|
||||
},
|
||||
name: 'password',
|
||||
order: 1,
|
||||
origin: {
|
||||
indexed: '2018-09-11T12:30:00Z',
|
||||
name: 'Dummy',
|
||||
},
|
||||
translations: {
|
||||
de: {
|
||||
categories: ['Anmeldedaten'],
|
||||
name: 'Passwort',
|
||||
},
|
||||
en: {
|
||||
categories: ['Credentials'],
|
||||
name: 'Password',
|
||||
},
|
||||
},
|
||||
type: 'setting',
|
||||
uid: '',
|
||||
},
|
||||
{
|
||||
categories: ['profile'],
|
||||
description: '',
|
||||
input: {
|
||||
defaultValue: 0,
|
||||
inputType: 'number',
|
||||
},
|
||||
name: 'age',
|
||||
order: 0,
|
||||
origin: {
|
||||
indexed: '2018-09-11T12:30:00Z',
|
||||
name: 'Dummy',
|
||||
},
|
||||
translations: {
|
||||
de: {
|
||||
categories: ['Profil'],
|
||||
name: 'Alter',
|
||||
},
|
||||
en: {
|
||||
categories: ['Profile'],
|
||||
name: 'Age',
|
||||
},
|
||||
},
|
||||
type: 'setting',
|
||||
uid: '',
|
||||
},
|
||||
{
|
||||
categories: ['profile'],
|
||||
description: '',
|
||||
input: {
|
||||
defaultValue: 'student',
|
||||
inputType: 'singleChoice',
|
||||
values: ['student', 'employee', 'guest'],
|
||||
},
|
||||
name: 'group',
|
||||
order: 1,
|
||||
origin: {
|
||||
indexed: '2018-09-11T12:30:00Z',
|
||||
name: 'Dummy',
|
||||
},
|
||||
translations: {
|
||||
de: {
|
||||
categories: ['Benutzer'],
|
||||
description: 'Mit welcher Benutzergruppe soll die App verwendet werden?'
|
||||
+ ' Die Einstellung wird beispielsweise für die Vorauswahl der Preiskategorie der Mensa verwendet.',
|
||||
name: 'Gruppe',
|
||||
},
|
||||
en: {
|
||||
categories: ['User'],
|
||||
description: 'The user group the app is going to be used.'
|
||||
+ 'This settings for example is getting used for the predefined price category of mensa meals.',
|
||||
name: 'Group',
|
||||
},
|
||||
},
|
||||
type: 'setting',
|
||||
uid: '',
|
||||
},
|
||||
{
|
||||
categories: ['profile'],
|
||||
description: '',
|
||||
input: {
|
||||
defaultValue: 'en',
|
||||
inputType: 'singleChoice',
|
||||
values: ['en', 'de'],
|
||||
},
|
||||
name: 'language',
|
||||
order: 0,
|
||||
origin: {
|
||||
indexed: '2018-09-11T12:30:00Z',
|
||||
name: 'Dummy',
|
||||
},
|
||||
translations: {
|
||||
de: {
|
||||
categories: ['Benutzer'],
|
||||
description: 'Die Sprache in der die App angezeigt werden soll',
|
||||
name: 'Sprache',
|
||||
},
|
||||
en: {
|
||||
categories: ['User'],
|
||||
description: 'The language this app is going to use',
|
||||
name: 'Language',
|
||||
},
|
||||
},
|
||||
type: 'setting',
|
||||
uid: '',
|
||||
},
|
||||
{
|
||||
categories: ['privacy'],
|
||||
description: '',
|
||||
input: {
|
||||
defaultValue: false,
|
||||
inputType: 'singleChoice',
|
||||
values: [true, false],
|
||||
},
|
||||
name: 'locationService',
|
||||
order: 0,
|
||||
origin: {
|
||||
indexed: '2018-09-11T12:30:00Z',
|
||||
name: 'Dummy',
|
||||
},
|
||||
translations: {
|
||||
de: {
|
||||
categories: ['Privatsphäre'],
|
||||
description: 'Berechtigung für die Verwendung des Ortungsdienstes, für die Anzeige der aktuellen ' +
|
||||
'Position \'\n auf der Karte und zur Berechnung der Entfernung zu Gebäuden und Orten des Campus',
|
||||
name: 'Position',
|
||||
},
|
||||
en: {
|
||||
categories: ['Privacy'],
|
||||
description: 'Allow the App to use the device location to provide additional informationsbased ' +
|
||||
'on your actual location',
|
||||
name: 'Position',
|
||||
},
|
||||
},
|
||||
type: 'setting',
|
||||
uid: '',
|
||||
},
|
||||
{
|
||||
categories: ['others'],
|
||||
description: '',
|
||||
input: {
|
||||
defaultValue: [],
|
||||
inputType: 'multipleChoice',
|
||||
values: [1, 2, 3, 4, 5, 6, 7, 8],
|
||||
},
|
||||
name: 'numbers',
|
||||
order: 0,
|
||||
origin: {
|
||||
indexed: '2018-09-11T12:30:00Z',
|
||||
name: 'Dummy',
|
||||
},
|
||||
translations: {
|
||||
de: {
|
||||
categories: ['Sonstiges'],
|
||||
description: 'Test für multiple select Feld',
|
||||
name: 'Nummern',
|
||||
},
|
||||
en: {
|
||||
categories: ['Others'],
|
||||
description: 'Test for multiple select field',
|
||||
name: 'Numbers',
|
||||
},
|
||||
},
|
||||
type: 'setting',
|
||||
uid: '',
|
||||
},
|
||||
];
|
||||
});
|
||||
297
src/app/modules/settingsProvider/settings.provider.ts
Normal file
297
src/app/modules/settingsProvider/settings.provider.ts
Normal file
@@ -0,0 +1,297 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {Injectable} from '@angular/core';
|
||||
import {SCSetting, SCSettingMultipleChoice, SCSettingSingleChoice, SCSettingValue} from '@openstapps/core';
|
||||
import {StorageProvider} from '../storage/storage.provider';
|
||||
|
||||
export const STORAGE_KEY_SETTINGS = 'settings';
|
||||
export const STORAGE_KEY_SETTINGS_SEPARATOR = '.';
|
||||
export const STORAGE_KEY_SETTING_VALUES = STORAGE_KEY_SETTINGS + STORAGE_KEY_SETTINGS_SEPARATOR + 'values';
|
||||
|
||||
/**
|
||||
* Category structure of settings cache
|
||||
*/
|
||||
export interface CategoryWithSettings {
|
||||
category: string;
|
||||
settings: { [key: string]: SCSetting };
|
||||
}
|
||||
|
||||
/**
|
||||
* Structure of SettingsCache
|
||||
*/
|
||||
export interface SettingsCache {
|
||||
[key: string]: CategoryWithSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider for app settings
|
||||
*/
|
||||
@Injectable()
|
||||
export class SettingsProvider {
|
||||
private categoriesOrder: string[];
|
||||
private initialized = false;
|
||||
private settingsCache: SettingsCache;
|
||||
|
||||
/**
|
||||
* Return true if all given values are valid to possible values in given settingInput
|
||||
* @param settingInput
|
||||
* @param values
|
||||
*/
|
||||
public static checkMultipleChoiceValue(settingInput: SCSettingMultipleChoice, values: SCSettingValue[]): boolean {
|
||||
for (const value of values) {
|
||||
if (!settingInput.values.includes(value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if given value is valid to possible values in given settingInput
|
||||
* @param settingInput
|
||||
* @param value
|
||||
*/
|
||||
public static checkSingleChoiceValue(settingInput: SCSettingSingleChoice, value: SCSettingValue): boolean {
|
||||
return settingInput.values !== undefined
|
||||
&& settingInput.values.includes(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates value for given settings inputType. Returns true if value is valid.
|
||||
* @param setting setting to check value against
|
||||
* @param value value to validate
|
||||
*/
|
||||
public static validateValue(setting: SCSetting, value: any): boolean {
|
||||
let isValueValid: boolean = false;
|
||||
switch (setting.input.inputType) {
|
||||
case 'number':
|
||||
if (typeof value === 'number') {
|
||||
isValueValid = true;
|
||||
}
|
||||
break;
|
||||
case 'multipleChoice':
|
||||
if (!value.isArray) {
|
||||
isValueValid = false;
|
||||
} else {
|
||||
isValueValid = SettingsProvider.checkMultipleChoiceValue(setting.input, value);
|
||||
}
|
||||
break;
|
||||
case 'password':
|
||||
case 'text':
|
||||
if (typeof value === 'string') {
|
||||
isValueValid = true;
|
||||
}
|
||||
break;
|
||||
case 'singleChoice':
|
||||
isValueValid = SettingsProvider.checkSingleChoiceValue(setting.input, value);
|
||||
break;
|
||||
default:
|
||||
}
|
||||
return isValueValid;
|
||||
}
|
||||
|
||||
constructor(public storage: StorageProvider) {
|
||||
this.categoriesOrder = [];
|
||||
this.settingsCache = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes settings cache from storage
|
||||
*/
|
||||
private async initSettings(): Promise<void> {
|
||||
try {
|
||||
this.settingsCache = await this.storage.get<SettingsCache>(STORAGE_KEY_SETTING_VALUES);
|
||||
for (const category of Object.keys(this.settingsCache)) {
|
||||
if (!this.categoriesOrder.includes(category)) {
|
||||
this.categoriesOrder.push(category);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
this.settingsCache = {};
|
||||
}
|
||||
await this.saveSettings();
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add category if not exists
|
||||
* @param category the category to provide
|
||||
*/
|
||||
private async provideCategory(category: string): Promise<void> {
|
||||
if (!this.categoryExists(category)) {
|
||||
if (!this.categoriesOrder.includes(category)) {
|
||||
this.categoriesOrder.push(category);
|
||||
}
|
||||
this.settingsCache[category] = {
|
||||
category: category,
|
||||
settings: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if category exists
|
||||
* @param category
|
||||
*/
|
||||
public categoryExists(category: string): boolean {
|
||||
return this.settingsCache[category] !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all provided settings
|
||||
*/
|
||||
public async clear(): Promise<void> {
|
||||
await this.init();
|
||||
this.settingsCache = {};
|
||||
await this.saveSettings();
|
||||
}
|
||||
|
||||
/**
|
||||
* returns an array with the order of categories
|
||||
*/
|
||||
public getCategoriesOrder(): string[] {
|
||||
return this.categoriesOrder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns copy of a setting if exist
|
||||
* @param category the category of requested setting
|
||||
* @param name the name of requested setting
|
||||
*
|
||||
* @throws Exception if setting is not provided
|
||||
*/
|
||||
public async getSetting(category: string, name: string): Promise<any> {
|
||||
await this.init();
|
||||
if (this.settingExists(category, name)) {
|
||||
return JSON.parse(JSON.stringify(this.settingsCache[category].settings[name]));
|
||||
} else {
|
||||
throw new Error('Setting "' + name + '" not provided');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns copy of cached settings
|
||||
*/
|
||||
public async getSettingsCache(): Promise<SettingsCache> {
|
||||
await this.init();
|
||||
return JSON.parse(JSON.stringify(this.settingsCache));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns copy of a setting if exist
|
||||
* @param category the category of requested setting
|
||||
* @param name the name of requested setting
|
||||
*
|
||||
* @throws Exception if setting is not provided
|
||||
*/
|
||||
public async getSettingValue(category: string, name: string): Promise<any> {
|
||||
await this.init();
|
||||
if (this.settingExists(category, name)) {
|
||||
return JSON.parse(JSON.stringify(this.settingsCache[category].settings[name].input.value));
|
||||
} else {
|
||||
throw new Error('Setting "' + name + '" not provided');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* initializes settingsProvider
|
||||
*/
|
||||
public async init(): Promise<void> {
|
||||
if (!this.initialized) {
|
||||
await this.initSettings();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds given setting and its category if not exist
|
||||
* @param setting the setting to add
|
||||
*/
|
||||
public async provideSetting(setting: SCSetting): Promise<void> {
|
||||
await this.init();
|
||||
if (!this.categoryExists(setting.categories[0])) {
|
||||
await this.provideCategory(setting.categories[0]);
|
||||
}
|
||||
if (!this.settingExists(setting.categories[0], setting.name)) {
|
||||
// set value to default
|
||||
if (setting.input.value === undefined) {
|
||||
setting.input.value = setting.input.defaultValue;
|
||||
}
|
||||
this.settingsCache[setting.categories[0]].settings[setting.name] = setting;
|
||||
await this.saveSettings();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets values of all settings to defaultValue
|
||||
*/
|
||||
public async resetDefault(): Promise<void> {
|
||||
await this.init();
|
||||
for (const catKey of Object.keys(this.settingsCache)) {
|
||||
for (const settingKey of Object.keys(this.settingsCache[catKey].settings)) {
|
||||
const settingInput = this.settingsCache[catKey].settings[settingKey].input;
|
||||
settingInput.value = settingInput.defaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves cached settings in app storage
|
||||
*/
|
||||
public async saveSettings(): Promise<void> {
|
||||
await this.storage.put(STORAGE_KEY_SETTING_VALUES, this.settingsCache);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the order the given categories showup in the settings page
|
||||
* @param categoryNames the order of the categories
|
||||
*/
|
||||
public setCategoriesOrder(categoryNames: string[]) {
|
||||
this.categoriesOrder = categoryNames;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a valid value of a setting and persists changes in storage
|
||||
* @param category
|
||||
* @param name
|
||||
* @param value
|
||||
*
|
||||
* @throws Exception if setting is not provided or value not valid to the settings inputType
|
||||
*/
|
||||
public async setSettingValue(category: string, name: string, value: any): Promise<void> {
|
||||
await this.init();
|
||||
if (this.settingExists(category, name)) {
|
||||
const setting: SCSetting = this.settingsCache[category].settings[name];
|
||||
const isValueValid = SettingsProvider.validateValue(setting, value);
|
||||
if (isValueValid) {
|
||||
this.settingsCache[category].settings[name].input.value = value;
|
||||
await this.saveSettings();
|
||||
} else {
|
||||
throw new Error('Value "' + value + '" of type ' +
|
||||
typeof value + ' is not valid for ' + setting.input.inputType);
|
||||
}
|
||||
} else {
|
||||
throw new Error('setting ' + name + ' is not provided');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if setting in category exists
|
||||
* @param category
|
||||
* @param setting
|
||||
*/
|
||||
public settingExists(category: string, setting: string): boolean {
|
||||
return this.categoryExists(category) && this.settingsCache[category].settings[setting] !== undefined;
|
||||
}
|
||||
}
|
||||
27
src/app/modules/settingsProvider/settingsProvider.module.ts
Normal file
27
src/app/modules/settingsProvider/settingsProvider.module.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import { NgModule } from '@angular/core';
|
||||
import { IonicStorageModule } from '@ionic/storage';
|
||||
import { SettingsProvider } from './settings.provider';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
IonicStorageModule.forRoot(),
|
||||
],
|
||||
providers: [
|
||||
SettingsProvider,
|
||||
],
|
||||
})
|
||||
export class SettingsProviderModule {}
|
||||
27
src/app/modules/storage/storage.module.ts
Normal file
27
src/app/modules/storage/storage.module.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import { NgModule } from '@angular/core';
|
||||
import { IonicStorageModule } from '@ionic/storage';
|
||||
import { StorageProvider } from './storage.provider';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
IonicStorageModule.forRoot()
|
||||
],
|
||||
providers: [
|
||||
StorageProvider
|
||||
]
|
||||
})
|
||||
export class StorageModule {}
|
||||
156
src/app/modules/storage/storage.provider.spec.ts
Normal file
156
src/app/modules/storage/storage.provider.spec.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {Storage} from '@ionic/storage';
|
||||
import {StorageModule} from './storage.module';
|
||||
import {StorageProvider} from './storage.provider';
|
||||
|
||||
describe('StorageProvider', () => {
|
||||
let storageProvider: StorageProvider;
|
||||
let storage: Storage;
|
||||
|
||||
const sampleEntries: Map<string, any> = new Map([
|
||||
['foo', 'Bar'],
|
||||
['bar', {foo: 'BarFoo'} as any],
|
||||
['foobar', 123],
|
||||
]);
|
||||
|
||||
beforeEach(async () => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [StorageModule],
|
||||
providers: [
|
||||
StorageProvider,
|
||||
// { provide: Storage, useClass: StorageMock }
|
||||
],
|
||||
});
|
||||
storageProvider = TestBed.get(StorageProvider);
|
||||
storage = TestBed.get(Storage);
|
||||
await storage.clear();
|
||||
});
|
||||
|
||||
it('should call ready method of storage on init', () => {
|
||||
spyOn(storage, 'ready');
|
||||
storageProvider.init();
|
||||
expect(storage.ready).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should call set method of storage to put a value', () => {
|
||||
spyOn(storage, 'set');
|
||||
storageProvider.put('some-uid', { some: 'thing' });
|
||||
expect(storage.set).toHaveBeenCalledWith('some-uid', { some: 'thing' });
|
||||
});
|
||||
|
||||
it('should call get method of storage to get a value', () => {
|
||||
spyOn(storage, 'get');
|
||||
storageProvider.get<any>('some-uid');
|
||||
expect(storage.get).toHaveBeenCalledWith('some-uid');
|
||||
});
|
||||
|
||||
it('should properly put and get a value', async () => {
|
||||
await storageProvider.init();
|
||||
await storageProvider.put('some-uid', {some: 'thing'});
|
||||
const result: Map<string, object> = await storageProvider.get<Map<string, object>>('some-uid');
|
||||
expect(result).toEqual({some: 'thing'});
|
||||
});
|
||||
|
||||
it('should throw an error when value is null', async () => {
|
||||
let error: Error = new Error();
|
||||
spyOn(storage, 'get').and.returnValue(Promise.resolve(null));
|
||||
try {
|
||||
await storageProvider.get('something-else');
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
expect(error).toEqual(new Error('Value not found.'));
|
||||
});
|
||||
|
||||
it('should put multiple values into the storage', async () => {
|
||||
spyOn(storageProvider, 'put');
|
||||
await storageProvider.putMultiple(sampleEntries);
|
||||
expect((storageProvider.put as jasmine.Spy).calls.count()).toEqual(3);
|
||||
expect(storageProvider.put).toHaveBeenCalledWith('foo', 'Bar');
|
||||
expect(storageProvider.put).toHaveBeenCalledWith('bar', {foo: 'BarFoo'});
|
||||
});
|
||||
|
||||
it('should get multiple values from the storage', async () => {
|
||||
spyOn(storageProvider, 'get').and.callThrough();
|
||||
await storageProvider.putMultiple(sampleEntries);
|
||||
const entries = await storageProvider.getMultiple(['foo', 'bar']);
|
||||
expect((storageProvider.get as jasmine.Spy).calls.count()).toEqual(2);
|
||||
expect(storageProvider.get).toHaveBeenCalledWith('foo');
|
||||
expect(storageProvider.get).toHaveBeenCalledWith('bar');
|
||||
expect(Array.from(entries.values())).toEqual(['Bar', {foo: 'BarFoo'}]);
|
||||
expect(Array.from(entries.keys())).toEqual(['foo', 'bar']);
|
||||
});
|
||||
|
||||
it('should get all values from the storage', async () => {
|
||||
spyOn(storageProvider, 'get').and.callThrough();
|
||||
await storageProvider.putMultiple(sampleEntries);
|
||||
const entries = await storageProvider.getAll();
|
||||
expect(Array.from(entries.values()).map((item) => (item.foo) ? item.foo : item).sort())
|
||||
.toEqual(Array.from(sampleEntries.values()).map((item) => (item.foo) ? item.foo : item).sort());
|
||||
expect(Array.from(entries.keys()).sort()).toEqual(['bar', 'foo', 'foobar']);
|
||||
});
|
||||
|
||||
it('should delete one entry', async () => {
|
||||
spyOn(storage, 'remove').and.callThrough();
|
||||
await storageProvider.putMultiple(sampleEntries);
|
||||
let entries = await storageProvider.getAll();
|
||||
expect(Array.from(entries.values()).length).toBe(3);
|
||||
await storageProvider.delete('bar');
|
||||
|
||||
expect(storage.remove).toHaveBeenCalled();
|
||||
entries = await storageProvider.getAll();
|
||||
expect(Array.from(entries.values())).toEqual(['Bar', 123]);
|
||||
});
|
||||
|
||||
it('should delete all entries in the storage', async () => {
|
||||
spyOn(storage, 'clear').and.callThrough();
|
||||
await storageProvider.putMultiple(sampleEntries);
|
||||
let entries = await storageProvider.getAll();
|
||||
expect(Array.from(entries.values()).length).toBe(3);
|
||||
await storageProvider.deleteAll();
|
||||
|
||||
entries = await storageProvider.getAll();
|
||||
expect(storage.clear).toHaveBeenCalled();
|
||||
expect(Array.from(entries.values()).length).toBe(0);
|
||||
});
|
||||
|
||||
it('should provide number of entries', async () => {
|
||||
spyOn(storage, 'length').and.callThrough();
|
||||
|
||||
expect(await storageProvider.length()).toBe(0);
|
||||
expect(storage.length).toHaveBeenCalled();
|
||||
|
||||
await storageProvider.putMultiple(sampleEntries);
|
||||
expect(await storageProvider.length()).toBe(3);
|
||||
});
|
||||
|
||||
it('should provide information if storage is empty', async () => {
|
||||
spyOn(storage, 'length').and.callThrough();
|
||||
|
||||
expect(await storageProvider.isEmpty()).toBeTruthy();
|
||||
expect(storage.length).toHaveBeenCalled();
|
||||
|
||||
await storageProvider.putMultiple(sampleEntries);
|
||||
expect(await storageProvider.isEmpty()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('should provide information if storage contains a specific entry (key)', async () => {
|
||||
spyOn(storage, 'keys').and.returnValue(Promise.resolve(Array.from(sampleEntries.keys())));
|
||||
expect(await storageProvider.has('foo')).toBeTruthy();
|
||||
expect(await storageProvider.has('something-else')).toBeFalsy();
|
||||
});
|
||||
});
|
||||
137
src/app/modules/storage/storage.provider.ts
Normal file
137
src/app/modules/storage/storage.provider.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
/*
|
||||
* Copyright (C) 2018 StApps
|
||||
* This program is free software: you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the Free
|
||||
* Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {Injectable} from '@angular/core';
|
||||
import {Storage} from '@ionic/storage';
|
||||
|
||||
/**
|
||||
* Provides interaction with the (ionic) storage on the device (in the browser)
|
||||
*/
|
||||
@Injectable()
|
||||
export class StorageProvider {
|
||||
constructor(private storage: Storage) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the storage (waits until it's ready)
|
||||
*/
|
||||
async init(): Promise<any> {
|
||||
return this.storage.ready();
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a value of type T into the storage using provided key
|
||||
*
|
||||
* @param key Unique indentifier
|
||||
* @param value Resource to store under the key
|
||||
*/
|
||||
async put<T>(key: string, value: T): Promise<T> {
|
||||
return this.storage.set(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a value from the storage using the provided key
|
||||
*
|
||||
* @param key Unique identifier of the wanted resource in storage
|
||||
*/
|
||||
async get<T>(key: string): Promise<T> {
|
||||
const entry = await this.storage.get(key);
|
||||
if (!entry) {
|
||||
throw new Error('Value not found.');
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a storage entry using the key used to save it
|
||||
*
|
||||
* @param key Unique identifier of the resource
|
||||
*/
|
||||
async delete(key: string): Promise<void> {
|
||||
return this.storage.remove(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all the entries in the storage (empty the storage)
|
||||
*/
|
||||
async deleteAll(): Promise<void> {
|
||||
return this.storage.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves multiple entries into the storage
|
||||
*
|
||||
* @param entries Resources to be put into the storage
|
||||
*/
|
||||
async putMultiple(entries: Map<string, any>): Promise<Map<string, any>> {
|
||||
const puts: Array<Promise<any>> = [];
|
||||
entries.forEach(async (value, key) => {
|
||||
puts.push(this.put(key, value));
|
||||
});
|
||||
await Promise.all(puts);
|
||||
return entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves multiple entries from the storage using their keys
|
||||
*
|
||||
* @param keys Unique identifiers of wanted resources from the storage
|
||||
*/
|
||||
async getMultiple(keys: string[]): Promise<Map<string, any>> {
|
||||
const gets: Array<Promise<any>> = [];
|
||||
const map = new Map();
|
||||
const getToMap = async (key: string) => {
|
||||
map.set(key, await this.get(key));
|
||||
}
|
||||
keys.forEach((key) => {
|
||||
gets.push(getToMap(key));
|
||||
});
|
||||
await Promise.all(gets);
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves all the storage entries
|
||||
*/
|
||||
async getAll(): Promise<Map<string, any>> {
|
||||
const map: Map<string, any> = new Map();
|
||||
await this.storage.forEach((value, key) => {
|
||||
map.set(key, value);
|
||||
});
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides a number of entries in the storage (number of keys)
|
||||
*/
|
||||
async length(): Promise<number> {
|
||||
return this.storage.length();
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides information if storage is empty or not
|
||||
*/
|
||||
async isEmpty(): Promise<boolean> {
|
||||
return (await this.storage.length()) === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides information if storage has an entry with the given key
|
||||
*
|
||||
* @param key Unique identifier of the resource in storage
|
||||
*/
|
||||
async has(key: string): Promise<boolean> {
|
||||
return (await this.storage.keys()).includes(key);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user