-
Notifications
You must be signed in to change notification settings - Fork 0
/
visits.js
92 lines (72 loc) · 2.29 KB
/
visits.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
const { Datastore } = require("@google-cloud/datastore");
const Fuse = require("fuse.js");
const { v4: uuid } = require("uuid");
const datastore = new Datastore();
const getVisit = async (visitId) => {
// create the db query of location entities
// filtering by visitId
const query = datastore
.createQuery("location")
.filter("visitId", "=", visitId);
// running the query and waiting for the repsonse
const data = await datastore.runQuery(query);
// cleaning out unneeded properties for response
return cleanData(data[0]);
};
// exported functions
const saveVisit = async (userId, location) => {
// database key needed for import
const locationKey = datastore.key("location");
// unique identifier for individual gets
const visitId = uuid();
// created date for recency sorting on search
const created = Date.now();
// creating entity
const visit = {
key: locationKey,
data: {
userId: userId,
name: location,
visitId: visitId,
visitDate: created,
},
};
// saving entity
await datastore.upsert(visit);
//return unique identifier
return { visitId: visitId };
};
const searchVisits = async (userId, searchString) => {
// retrieve the visits by user before sorting and searching
const data = await listVisits(userId);
// sort by most recent and return the 5 most recent
let sortedData = sortVisits(data[0]);
// fuzzy search the sorted list
const fuse = new Fuse(sortedData, {
keys: ['name']
});
const searched = fuse.search(searchString);
// clean the searched list for response
return cleanData(searched.map(s => s.item));
};
// helpers
const cleanData = (visits) => {
// visit date is only used for sorting by date not needed in response
visits.forEach((visit) => {
delete visit.visitDate;
});
return visits;
};
// gets all visits by user
const listVisits = (userId) => {
const query = datastore.createQuery("location").filter("userId", "=", userId);
return datastore.runQuery(query);
};
// sorts visits by date
const sortVisits = (visits) => {
let sortedData = visits.sort((a, b) => (a.visitDate > b.visitDate ? -1 : 1));
return sortedData.length > 5 ? sortedData.slice(0,5) : sortedData;
};
exports.getVisit = getVisit;
exports.searchVisits = searchVisits;
exports.saveVisit = saveVisit;