-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
106 lines (79 loc) · 2.99 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import 'react-native-gesture-handler';
import React from 'react';
import {createServer} from "miragejs"
import AsyncStorage from '@react-native-async-storage/async-storage';
import Router from './app/router';
const STORAGE_KEY = "@trades";
if (window.server) {
server.shutdown()
}
async function getTrades() {
let trades = await AsyncStorage.getItem(STORAGE_KEY);
trades = (trades !== null) ? JSON.parse(trades) : [];
return trades;
}
window.server = createServer({
routes() {
this.get("/api/trade", async () => {
try {
let trades = await getTrades();
return {trades}
} catch (e) {
return {success: false, message: e}
}
});
this.post("/api/trade", async (schema, request) => {
try {
//get the trades array
let trades = await getTrades();
//get the new trade data
let trade = JSON.parse(request.requestBody);
//push the the new trade into the trades arra
trades.push(trade);
//update the storage
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(trades));
return {trade, message: 'Trade added successfully'};
} catch (e) {
return {success: false, message: e}
}
});
this.put("/api/trade/:id", async (schema, request) => {
try {
//get the id
let id = request.params.id;
//get the trades array
let trades = await getTrades();
//get the updated trade data
let trade = JSON.parse(request.requestBody);
//Find the trade using the id, if found update the trade using its index
const index = trades.findIndex((obj) => obj.id === id);
if (index !== -1) trades[index] = {...trades[index], ...trade};
//update the storage
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(trades));
return {trade, message: 'Trade updated successfully'};
} catch (e) {
return {success: false, message: e}
}
});
this.del("/api/trade/:id", async (schema, request) => {
try {
//get the id
let id = request.params.id;
//get the trades array
let trades = await getTrades();
//Find the trade using the id and remove it from the trades array
trades = trades.filter((obj) => obj.id !== id);
//update the storage
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(trades));
return {message: 'Trade deleted successfully'};
} catch (e) {
return {success: false, message: e}
}
})
},
});
export default function App() {
return (
<Router/>
);
}