Skip to content

Commit ea8acde

Browse files
author
Pierre-Florent Poujol
committed
api get response ok & implement get products request
1 parent c7ffa44 commit ea8acde

File tree

4 files changed

+63
-59
lines changed

4 files changed

+63
-59
lines changed

functions/src/index.ts

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -22,17 +22,20 @@ const promoCollection = 'promotions';
2222
//define google cloud function name
2323
export const webServices = functions.region('europe-west1').https.onRequest(main);
2424

25-
// https://europe-west1-mspr-gostyleapp.cloudfunctions.net/webServices/api/promotions/Extra10
25+
2626
app.get('/promotions/:promoId', (req, res) => {
2727

2828
const promoId = req.params.promoId;
2929
db.collection(promoCollection).doc(promoId).get()
3030
.then(promo => {
3131
if (!promo.exists) {
32-
res.status(400).json({error: 'Promotion introuvable.'});
32+
res.status(400).json({
33+
status : 'error',
34+
message: 'Promotion introuvable.'
35+
});
3336
} else {
3437
res.status(200).json({
35-
id: promo.id,
38+
status : "success",
3639
data: {
3740
code: promo.data()?.code,
3841
dateExpiration: promo.data()?.dateExpiration.toDate(),
@@ -63,7 +66,6 @@ app.post('/promotions', (req, res) => {
6366
description: body.description
6467
};
6568
db.collection(promoCollection).doc(promo.code).get().then(doc => {
66-
console.log(doc)
6769
if (doc.exists) {
6870
res.status(400).send('Cette promotion existe déjà.');
6971
} else {
@@ -76,29 +78,31 @@ app.post('/promotions', (req, res) => {
7678

7779
}
7880
} catch (error) {
79-
console.log('error');
8081
res.status(400).send('La promotion doit contenir les valeurs suivantes : "code", "dateExpiration", "description"');
8182
}
8283
});
8384

8485
app.delete('/promotions/:promoId', async (req, res) => {
8586
await db.collection(promoCollection).doc(req.params.promoId).delete();
86-
res.status(200).send('La promotion a bien été supprimée !');
87+
res.status(204).send({});
8788
});
8889

8990
app.get('/users/:userId', (req, res) => {
9091
const userId = req.params.userId;
9192
db.collection(userCollection).doc(userId).get()
9293
.then(user => {
9394
if (!user.exists) {
94-
res.status(400).json({error: 'Utilisateur introuvable.'});
95+
res.status(400).json({
96+
status : 'error',
97+
message: 'Utilisateur introuvable.'
98+
});
9599
}
96100
res.status(200).json({
97-
id: user.id,
101+
status : "success",
98102
data: {
99103
uid: user.id,
100104
name: user.data()?.name,
101-
firstname: user.data()?.firstname,
105+
firstname: user.data()?.firstname
102106
}
103107
});
104108
}).catch(error => res.status(500).send(error));
@@ -109,24 +113,27 @@ app.get('/users/:userId/promotions', (req, res) => {
109113
db.collection(userCollection).doc(userId).get()
110114
.then(user => {
111115
if (!user.exists) {
112-
res.status(400).json({error: 'Utilisateur introuvable.'});
116+
res.status(400).json({
117+
status : 'error',
118+
message: 'Utilisateur introuvable.'
119+
});
113120
}
114121
const promises = Object.keys(user.data()?.ownedPromos).map(promoId => db.collection(promoCollection).doc(promoId).get());
115122
Promise.all(promises).then(promosSnapshot => {
116123
const promotions: any[] = [];
117124
promosSnapshot.forEach(promo => {
118125
if (promo.exists) {
119126
promotions.push({
120-
id: promo.id,
121-
data: {
122-
code: promo.data()?.code,
123-
dateExpiration: promo.data()?.dateExpiration.toDate(),
124-
description: promo.data()?.description
125-
}
127+
code: promo.data()?.code,
128+
dateExpiration: promo.data()?.dateExpiration.toDate(),
129+
description: promo.data()?.description
126130
});
127131
}
128132
});
129-
res.status(200).json(promotions);
133+
res.status(200).json({
134+
status : "success",
135+
data: promotions
136+
});
130137
}).catch(error => res.status(500).send(error));
131138
}).catch(error => res.status(500).send(error));
132139
});

src/app/app.module.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,12 @@ import { StatusBar } from '@ionic-native/status-bar/ngx';
77

88
import { AppComponent } from './app.component';
99
import { AppRoutingModule } from './app-routing.module';
10+
import {HttpClientModule} from '@angular/common/http';
1011

1112
@NgModule({
1213
declarations: [AppComponent],
1314
entryComponents: [],
14-
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
15+
imports: [BrowserModule, HttpClientModule, IonicModule.forRoot(), AppRoutingModule],
1516
providers: [
1617
StatusBar,
1718
SplashScreen,

src/app/home/home.page.ts

Lines changed: 16 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -46,56 +46,43 @@ export class HomePage implements OnInit, OnDestroy {
4646
this.authService.getPromisedUser().then(user => {
4747
this.userId = user.uid;
4848
return user;
49-
}).then(user => this.getPromos(user.uid));
49+
}).then(user => {
50+
this.initUserPromos(user.uid);
51+
});
5052
}
5153

5254
/**
53-
* Obtention de la liste des promotions de l'utilisateur ordonnée par date d'expiration
55+
* Affichage message de bienvenue, et optention des promos si infos utilisateur completés.
5456
*/
55-
getPromos(uid: string) {
57+
initUserPromos(uid: string) {
5658
this.subscriptions = this.afs.doc<UserFirestore>('users/' + uid).valueChanges().subscribe(action => {
5759
if (this.itInit && action !== undefined) {
5860
this.presentToast(`<ion-icon name="happy"></ion-icon> Bienvenue ${action.firstname} ${action.name} !`);
5961
}
6062
if (action !== undefined) {
6163
this.itInit = false;
6264
this.mapPromos = action.ownedPromos;
63-
const arrPromos = Object.keys(action.ownedPromos);
64-
if (arrPromos.length > 0) {
65-
const subscription = this.promosService.getPromos(arrPromos).pipe(
66-
map(actions => actions.map(a => {
67-
return {
68-
code: a.payload.doc.id,
69-
dateExpiration: a.payload.doc.data().dateExpiration.toDate(),
70-
description: a.payload.doc.data().description
71-
};
72-
}))
73-
).subscribe(promos => {
74-
this.promos = promos;
75-
});
76-
this.subscriptions.add(subscription);
77-
} else {
78-
this.msgArrIsEmpty = 'Vous ne possédez aucune promotion.';
79-
this.promos = [];
80-
}
65+
const subscription = this.promosService.getPromosAPI(uid).subscribe(response => {
66+
if (response.status === 'success') {
67+
this.promos = response.data.sort((a, b) => a.dateExpiration.getTime() - b.dateExpiration.getTime());
68+
if (response.data.length === 0) {
69+
this.msgArrIsEmpty = 'Vous ne possédez aucune promotion en cours.';
70+
}
71+
} else if (response.status === 'error') {
72+
this.presentAlert(response.message);
73+
}
74+
});
75+
this.subscriptions.add(subscription);
8176
} else {
8277
this.msgArrIsEmpty = 'Vous devez compléter votre compte.';
8378
this.presentAlertPrompt(this.userId);
8479
}
85-
8680
});
8781
}
8882

8983
/**
9084
* Obtention des infos de l'utilisateur depuis Firebase Authentification + Cloud FireStore
9185
*/
92-
checkAccount() {
93-
this.afs.doc('users/' + this.userId).ref.get().then((snapshot: DocumentSnapshot<UserFirestore>) => {
94-
if ( !snapshot.exists ) {
95-
this.presentAlertPrompt(this.userId);
96-
}
97-
});
98-
}
9986

10087
scanCode() {
10188
this.barcodeScanner

src/app/services/promos.service.ts

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,40 @@
11
import {Injectable} from '@angular/core';
22
import {AngularFirestore, DocumentChangeAction, DocumentReference} from '@angular/fire/firestore';
33
import {Observable} from 'rxjs';
4+
5+
import {HttpClient} from '@angular/common/http';
46
import {PromotionFirestore} from '../models/firestore/PromotionFirestore';
7+
import {Promotion} from '../models/Promotion';
58

69
@Injectable({
710
providedIn: 'root'
811
})
12+
export interface ResponseSuccess {
13+
status: 'success';
14+
data: Array<Promotion>;
15+
}
16+
export interface ResponseError {
17+
status: 'error';
18+
message: string;
19+
}
920
export class PromosService {
1021

11-
constructor(private firestore: AngularFirestore) {
22+
constructor(private http: HttpClient, private firestore: AngularFirestore) {
1223
}
1324

14-
getPromo(codePromo: string): DocumentReference {
25+
getPromoAFS(codePromo: string): DocumentReference {
1526
return this.firestore.collection('promotions').doc(codePromo).ref;
1627
}
1728

18-
/**
19-
* TODO: Ordonner par user range
20-
*/
21-
getPromos(array: Array<string>): Observable<DocumentChangeAction<PromotionFirestore>[]> {
29+
getPromosAFS(array: Array<string>): Observable<DocumentChangeAction<PromotionFirestore>[]> {
2230
return this.firestore.collection<PromotionFirestore>('promotions', ref => ref
23-
.where('dateExpiration', '>', new Date())
24-
.where('code', 'in', array))
25-
.snapshotChanges();
31+
.where('dateExpiration', '>', new Date())
32+
.where('code', 'in', array))
33+
.snapshotChanges();
2634
}
2735

28-
/* getUser(): DocumentReference {
29-
return this.firestore.collection('users').doc('goEdwr6nOpN0oyiAGWvs9vFWaSj1').ref;
30-
}*/
36+
getPromosAPI(uid: string): Observable<ResponseSuccess | ResponseError> {
37+
const url = 'https://europe-west1-mspr-gostyleapp.cloudfunctions.net/webServices/v1/users/' + uid + '/promotions';
38+
return this.http.get<ResponseSuccess | ResponseError>(url);
39+
}
3140
}

0 commit comments

Comments
 (0)