Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
991 lines (915 loc) · 34.4 KB
/
Copy pathindex.js
File metadata and controls
991 lines (915 loc) · 34.4 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
'use strict';
const createRouter = require('@arangodb/foxx/router');
const joi = require('joi');
const db = require('@arangodb').db;
const errors = require('@arangodb').errors;
const aql = require('@arangodb').aql;
let request = require('@arangodb/request');
const crypto = require('@arangodb/crypto');
const hostname = require('./config').hostname;
const spreadsheetId = require('./config').calculateSpreadsheetId;
const apiKey = require('./config').calculateApiKey;
const sessionsMiddleware = require('@arangodb/foxx/sessions');
const DOC_NOT_FOUND = errors.ERROR_ARANGO_DOCUMENT_NOT_FOUND.code;
const projects = db._collection('projects');
const snapshots = db._collection('snapshots');
const objects = db._collection('objects');
const materials = db._collection('materials');
const orders = db._collection('orders');
const users = db._collection('users');
const projectRelation = db._collection('project_relation');
const router = createRouter();
const sessions = sessionsMiddleware({
storage: db._collection('sessions'),
transport: 'header'
});
module.context.use(router);
module.context.use(sessions);
router.use('/docs', module.context.createDocumentationRouter(function (req, res) {
// if (req.suffix === 'swagger.json' && !req.arangoUser) {
// res.throw(401, 'Not authenticated');
// }
return {
indexFile: "index.html",
mount: req.context.mount
}
}));
/**
* handle unauthorized user
*/
module.context.use(function (req, res, next) {
const exclusion = ['/get-materials-thermevo'];
if (!req.session.uid && exclusion.indexOf(req.path) == -1 && !/docs/.test(req.path)) {
res.throw(401, 'Unauthorized user');
}
next();
});
router.get('/project/:key', function (req, res) {
try {
const user = users.document(req.session.uid);
const result = db._query(aql`
FOR project IN OUTBOUND ${user._id} ${projectRelation}
FILTER project._key == ${req.pathParams.key}
LET snaps =( FOR snapshot IN ${snapshots}
FILTER snapshot.projectKey == ${req.pathParams.key} AND !snapshot.deleted
SORT snapshot.createdAt
LET objs = (
FOR items IN objects
FILTER items.snapshotKey == snapshot._key
RETURN {
_key: items._key,
title: items.title,
createdBy: items.createdBy,
createdAt: items.createdAt
}
)
RETURN {_key: snapshot._key,
_id: snapshot._id,
_rev: snapshot._rev,
title: snapshot.title,
createdAt: snapshot.createdAt,
createdBy: snapshot.createdBy,
objects: objs
}
)
RETURN {_key: project._key,
_id: project._id,
_rev: project._rev,
title: project.title,
fileName: project.fileName,
createdAt: project.createdAt,
status: project.status,
snapshots: snaps
}
`);
res.send(result)
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.pathParam('key', joi.string().required(), 'Key of the project.')
.response(joi.object().required(), 'Project stored in the collection "projects".')
.summary('Retrieve an project by key authorized user ')
.description('Retrieves an project from the "projects" collection by key if user have authorized');
/**
* POST /project-archive
*/
const projectArchiveBodyModel = {
key: joi.string().required(),
status: joi.string().required(),
};
router.post('/project-archive', function (req, res) {
try {
const user = users.document(req.session.uid);
const key = req.body.key;
const status = req.body.status;
const result = db._query(aql`
FOR project IN OUTBOUND ${user._id} ${projectRelation}
FILTER project._key == ${key}
UPDATE project WITH { status: ${status} } IN ${projects}
LET newProject = NEW
LET snaps =( FOR snapshot IN ${snapshots}
FILTER snapshot.projectKey == ${key} AND !snapshot.deleted
SORT snapshot.createdAt
LET objs = (
FOR items IN objects
FILTER items.snapshotKey == snapshot._key
RETURN {
_key: items._key,
title: items.title,
createdBy: items.createdBy,
createdAt: items.createdAt
}
)
RETURN {_key: snapshot._key,
_id: snapshot._id,
_rev: snapshot._rev,
title: snapshot.title,
createdAt: snapshot.createdAt,
createdBy: snapshot.createdBy,
objects: objs
}
)
RETURN {_key: newProject._key,
_id: newProject._id,
_rev: newProject._rev,
title: newProject.title,
fileName: newProject.fileName,
createdAt: newProject.createdAt,
status: newProject.status,
snapshots: snaps
}
`);
res.send(...result)
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.response(joi.object().required(), 'Returns the updated project stored in the collection.')
.body(projectArchiveBodyModel, ['application/json'])
.summary('Change status project.')
.description('Change status project. Retrieves an project from the "projects" collection by key. User must be authorized.');
/**
* POST /add-project
*/
const addProjectBodyModel = joi.array().items(joi.object().required()).required();
router.post('/add-project', function (req, res) {
try {
const user = users.document(req.session.uid);
const parts = req.body;
const file = parts[0].data.toString();
const title = parts[1].data.toString();
const fileName = parts[2].data.toString();
const addProject = db._query(aql`
LET exist = (FOR p IN OUTBOUND ${user._id} ${projectRelation}
FILTER p.title == ${title}
RETURN p._key)
FILTER LENGTH(exist) < 1
LET project = (INSERT {title: ${title},
createdAt: DATE_NOW(),
fileName: ${fileName},
status: "active",
file: ${file}
} IN projects
RETURN NEW)
LET relation = (INSERT {_from: ${user._id},
_to: project[0]._id,
"role": "owner"}
IN project_relation
RETURN NEW)
RETURN project[0]._key
`);
res.send({_key: addProject._documents[0].toString()})
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.response(joi.object().required(), 'Returns new project key saved in db.')
.body(addProjectBodyModel, ['multipart/form-data'])
.summary('Add new project.')
.description('Add new project to projects and add project-key to registered user.');
/**
* GET /project-file/:projectKey
*/
router.get('/project-file/:projectKey', function (req, res) {
try {
const user = users.document(req.session.uid);
const key = req.pathParams.projectKey.toString();
const result = db._query(aql`
FOR projects IN OUTBOUND ${user._id} ${projectRelation}
FILTER projects._key == ${key}
RETURN projects.file
`);
res.send(...result);
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.response(joi.object().required(), 'Returns project data file.')
.pathParam('projectKey', joi.string().required(), 'Project key.')
.summary('Get project DXF file data.')
.description('Returns project dxf file data.');
/**
* GET /projects-list/:filter
*/
router.get('/projects-list/:filter', function (req, res) {
try {
const user = users.document(req.session.uid);
const filter = req.pathParams.filter.toString();
let result;
if (filter === 'active' || filter === 'archive') {
result = db._query(aql`
FOR projects IN OUTBOUND ${user._id} ${projectRelation}
FILTER projects.status == ${filter}
RETURN {_key: projects._key,
_id: projects._id,
_rev: projects._rev,
title: projects.title,
fileName: projects.fileName,
createdAt: projects.createdAt,
status: projects.status
}
`);
} else {
result = db._query(aql`
FOR projects IN OUTBOUND ${user._id} ${projectRelation}
RETURN {_key: projects._key,
_id: projects._id,
_rev: projects._rev,
title: projects.title,
fileName: projects.fileName,
createdAt: projects.createdAt,
status: projects.status
}
`);
}
res.send(result)
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.response(joi.array().items(joi.object().required()).required(), 'Returns projects array.')
.pathParam('filter', joi.string().required(), 'Parameter: active, archive filter projects, else parameter return all user projects')
.summary('Get project list.')
.description('Returns users projects list.');
/**
* POST /add-snapshot/:projectKey
*/
router.post('/add-snapshot/:projectKey', function (req, res) {
try {
const user = users.document(req.session.uid);
let key = req.pathParams.projectKey.toString();
const snapshot = snapshots.insert({
title: req.body.title,
createdBy: user._key,
projectKey: key,
createdAt: Date.now(),
layers: req.body.layers
}
);
req.body.objects.forEach(item => {
objects.insert({
title: item.title,
createdBy: user._key,
snapshotKey: snapshot._key,
projectKey: key,
createdAt: Date.now(),
parameters: item.parameters
}
)
}
);
const snaps = db._query(aql`
FOR snapshot IN ${snapshots}
FILTER snapshot.projectKey == ${key} AND
!snapshot.deleted AND
snapshot._key == ${snapshot._key}
LET objs = (
FOR items IN objects
FILTER items.snapshotKey == ${snapshot._key}
RETURN {
_key: items._key,
title: items.title,
createdBy: items.createdBy,
createdAt: items.createdAt
}
)
RETURN {_key: snapshot._key,
_id: snapshot._id,
_rev: snapshot._rev,
title: snapshot.title,
createdAt: snapshot.createdAt,
createdBy: snapshot.createdBy,
objects: objs
}
`);
res.send(snaps._documents[0]);
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.response(joi.object().required().keys(
{
_key: joi.string().required(),
_id: joi.string().required(),
_rev: joi.string().required(),
title: joi.string().required(),
createdAt: joi.string().required(),
createdBy: joi.string().required(),
objects: joi.array().items(joi.object().optional()).required()
}
).unknown(), 'Return snapshot.')
.body(
{
title: joi.string().required(),
layers: joi.string().required(),
objects: joi.array().items(joi.object().optional()).required()
},
['application/json'])
.pathParam('projectKey', joi.string().required(), 'project key.')
.summary('Add snapshot to project.')
.description('Add snapshot to project.');
/**
* GET /get-snapshots/:projectKey
*/
router.get('/get-snapshots/:projectKey', function (req, res) {
try {
const key = req.pathParams.projectKey.toString();
const result = db._query(aql`
FOR snapshot IN ${snapshots}
FILTER snapshot.projectKey == ${key} AND !snapshot.deleted
RETURN {_key: snapshot._key,
_id: snapshot._id,
_rev: snapshot._rev,
title: snapshot.title,
createdAt: snapshot.createdAt,
createdBy: snapshot.createdBy
}
`);
res.send(result);
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.pathParam('projectKey', joi.string().required(), 'project key.')
.response(joi.array().items(joi.object().required().keys({
_key: joi.string().required(),
_id: joi.string().required(),
_rev: joi.string().required(),
title: joi.string().required(),
createdAt: joi.string().required(),
createdBy: joi.string().required()
})).required(), 'Returns snapshots array.')
.summary('Returns array snapshots.')
.description('Returns array snapshots data.');
/**
* GET /snapshot/:snapshotKey
*/
router.get('/snapshot/:snapshotKey', function (req, res) {
try {
const key = req.pathParams.snapshotKey.toString();
const snapshot = db._query(aql`
FOR snapshot IN ${snapshots}
FILTER snapshot._key == ${key}
LET objs = (
FOR items IN ${objects}
FILTER items.snapshotKey == ${key}
SORT items.title
RETURN items
)
RETURN {_key: snapshot._key,
_id: snapshot._id,
_rev: snapshot._rev,
title: snapshot.title,
createdAt: snapshot.createdAt,
createdBy: snapshot.createdBy,
layers: snapshot.layers,
objects: objs
}
`);
res.send(snapshot._documents[0])
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.pathParam('snapshotKey', joi.string().required(), 'snapshot key.')
.response(joi.object().required().keys({
_key: joi.string().required(),
_id: joi.string().required(),
_rev: joi.string().required(),
title: joi.string().required(),
createdAt: joi.string().required(),
createdBy: joi.string().required(),
layers: joi.string().required(),
objects: joi.array().required()
}).required(), 'Return snapshot object.')
.summary('Return snapshot by key.')
.description('Return snapshot by key.');
/**
* GET /object-snapshot/:objectKey
*/
router.get('/object-snapshot/:objectKey', function (req, res) {
try {
let object = objects.document(req.pathParams.objectKey);
res.send(object)
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.pathParam('objectKey', joi.string().required(), 'object key.')
.response(joi.object().required().keys({
_key: joi.string().required(),
_id: joi.string().required(),
_rev: joi.string().required(),
title: joi.string().required(),
snapshotKey: joi.string().required(),
projectKey: joi.string().required(),
parameters: joi.string().required(),
createdAt: joi.string().required(),
createdBy: joi.string().required()
}).required(), 'Return snapshot object.')
.summary('Return object snapshot.')
.description('Return object snapshot from objects collections.');
/**
* DELETE /del-snapshot/:snapshotKey
*/
router.delete('/snapshot/:snapshotKey', function (req, res) {
try {
const key = req.pathParams.snapshotKey.toString();
const result = db._query(aql`
REMOVE { _key: ${key}} IN ${snapshots}
FOR items IN ${objects}
FILTER items.snapshotKey == ${key}
REMOVE items IN ${objects}
`);
result._documents.length === 0 ? res.send({success: 'Success remove snapshot & objects.'}) : res.send(result)
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.pathParam('snapshotKey', joi.string().required(), 'snapshot key.')
.response(joi.object().required().keys({
success: joi.object()
}).required(), 'Return snapshot object.')
.summary('Delete snapshot.')
.description('Delete snapshot by key.');
/**
* GET /get-materials-thermevo
*/
router.get('/get-materials-thermevo', function (req, res) {
try {
const response = request(
{
method: 'POST',
url: 'https://thermevo.de/api/get_material_json',
body: {},
json: true
});
const getmaterials = response.json.result.O.map(material => {
return {
id: material[0],
name: material[1],
density: material[2],
lambda: material[3],
epsilon: material[4],
color: material[5],
state: material[6],
type: material[7],
group: material[8]
}
});
const result = materials.insert(getmaterials, {returnNew: true});
res.send(result)
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.summary('Get materials from thermevo.de')
.description('Get materials from thermevo.de and save to DB in "materials" collection.');
/**
* GET /materials
*/
router.get('/materials', function (req, res) {
try {
const result = materials.all();
res.send(result)
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.response(joi.array().items(joi.object().required().keys({
_key: joi.string().required(),
_id: joi.string().required(),
_rev: joi.string().required(),
type: joi.string().required(),
state: joi.string().required(),
name: joi.string().required(),
lambda: joi.number().required(),
id: joi.string().required(),
group: joi.number().required(),
epsilon: joi.number().required(),
density: joi.number().required(),
color: joi.string().required()
})).required(), 'Returns materials array.')
.summary('Get materials from DB')
.description('Get materials from DB.');
/**
* POST /calculate
*/
router.post('/calculate', function (req, res) {
try {
const authorization = request.get(`${hostname}_db/cad/auth/access`).body;
//"range" for get info how to use: https://developers.google.com/sheets/api/samples/reading
const priceCells = `Input!BE5:BK5`;
const urlPriceResult = `https://content-sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${priceCells}?key=${apiKey}`;
let getPrice = (options) => {
let defaultParams = {
'result!L2': options.width, //width
'result!M2': options.height, //Height
'result!N2': options.area, //Area
'result!O2': options.type, //Typ
// 'result!B2': '/website/image/product.product/35408_2ac58e7/image', //Link to preview
'result!C2': '6', //length
'result!D2': 'PaStandard', //material
'result!E2': 'webCad-test', //?? Order№
'result!F2': 'webCad user', //?? Link to a client
'result!G2': new Date().toISOString().replace('-', '_').substr(0, 10), // date
'result!H2': 0, //number of seats
'result!I2': 10000, //order amount
'result!J2': 0, //annual contract amount
'result!K2': 0, //country
'result!P2': 0, //Gluewire
'result!Q2': 0, //Protection foil for powder coating
'result!R2': 0, //E-low
'result!S2': 0, //Soundblasting
'result!T2': 0, //Punching
// ...params
};
let data = [];
Object.keys(defaultParams).forEach(range => {
data.push({
range,
values: [[
defaultParams[range]
]]
})
});
const setCell = request(
{
method: 'POST',
url: `https://content-sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values:batchUpdate?alt=json&key=${apiKey}`,
body: {
"valueInputOption": "RAW",
"data": data
},
headers: {
'authorization': authorization,
'Content-Type': 'application/json',
'x-referer': 'https://explorer.apis.google.com'
},
json: true,
});
const responsePrice = request(
{
method: 'GET',
url: urlPriceResult,
headers: {'authorization': authorization}
});
if (!responsePrice.json || !responsePrice.json.values) {
return ({
setCell: setCell.json,
getPrice: responsePrice.json
});
} else {
return {
price: responsePrice.json.values[0][0],
minOrderQty: responsePrice.json.values[0][6]
}
}
};
let objects = req.body;
const price = [];
objects.forEach(option => {
price.push(getPrice(option));
});
res.send(price);
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.body(joi.array().items(joi.object().required().keys({
area: joi.number().required(),
height: joi.number().required(),
type: joi.number().required(),
weight: joi.number().required(),
width: joi.number().required()
})).required(), ['application/json'])
.response(joi.array().items(joi.object().required().keys({
price: joi.string().required(),
minOrderQty: joi.string().required()
})).required(), 'Returns array with price, minOrderQty.')
.summary('Get price, min order')
.description('Get price, min order for each object.');
/**
* DELETE /del-snapshot/:snapshotKey
*/
router.delete('/project/:projectKey', function (req, res) {
try {
const key = req.pathParams.projectKey.toString();
projects.remove({_key: key});
snapshots.removeByExample({projectKey: key});
projectRelation.removeByExample({_to: `projects/${key}`});
res.send('Project success removed');
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.pathParam('projectKey', joi.string().required(), 'projectKey key.')
.summary('Delete project')
.description('Delete project and all snapshots.');
// ========= get /user picture_url ====================
/**
* GET /picture-url
*/
router.get('/picture-url', function (req, res) {
try {
const user = users.document(req.session.uid);
res.send(user.picture_url ? user.picture_url : '');
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.response(joi.string().required(), 'Returns array with price, minOrderQty.')
.summary('Get user picture-url')
.description('Get user picture-url from DB.');
/**
* POST /order
*/
router.post('/order', function (req, res) {
try {
const user = users.document(req.session.uid);
const hash = crypto.jwtEncode('orderbestkey', user._key, 'HS256');
const order = orders.insert({
createdBy: user._key,
createdAt: Date.now(),
contactInformation: req.body.contactInformation,
order: req.body.order,
orderObjects: req.body.orderObjects,
hash
}
);
if (order._key) {
res.send({
message: `Your order is accepted. Thank you.`,
link: `${hostname}order/${order._key}/${hash}`
});
} else {
res.send(order);
}
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.body(
{
contactInformation: joi.object().required().keys({
addressCity: joi.string().required(),
addressCountry: joi.string().required(),
addressStreet: joi.string().required(),
comment: joi.string().required(),
company: joi.string().required(),
emailAddress: joi.string().required(),
firstName: joi.string().required(),
lastName: joi.string().required(),
phoneNumber: joi.string().required(),
zipCode: joi.string().required()
}),
order: joi.array().items(joi.object().required().keys({
material: joi.object().required(),
options: joi.object().required().keys({
checked: joi.boolean().required(),
color: joi.string().required(),
laserMarking: joi.boolean().required(),
length: joi.string().required(),
orderQty: joi.string().required(),
type: joi.string().required()
})
})).required(),
orderObjects: joi.array().items(joi.object().required().keys({
geometries: joi.array().required(),
materials: joi.array().required(),
metadata: joi.object().required(),
object: joi.object().required()
}))
},
['application/json']
)
.response(joi.object().required().keys({
message: joi.string(),
link: joi.string()
}), 'Returns succes message and link to the order.')
.summary('Process order')
.description('Process order from client.');
/**
* GET /order/:orderKey/:hash
*/
router.get('/order/:orderKey/:hash', function (req, res) {
try {
// const user = users.document(req.session.uid);
const key = req.pathParams.orderKey.toString();
const hash = req.pathParams.hash.toString();
const order = orders.document(key);
if (hash === order.hash) {
res.send(order);
} else {
res.throw(404, `You don't have permission to access this order`);
}
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.pathParam('orderKey', joi.string().required(), 'order key.')
.pathParam('hash', joi.string().required(), 'hash.')
.response(joi.object().required().keys({
_rev: joi.string().required(),
_key: joi.string().required(),
_id: joi.string().required(),
hash: joi.string().required(),
createdBy: joi.string().required(),
createdAt: joi.string().required(),
contactInformation: joi.object().required().keys({
addressCity: joi.string().required(),
addressCountry: joi.string().required(),
addressStreet: joi.string().required(),
comment: joi.string().required(),
company: joi.string().required(),
emailAddress: joi.string().required(),
firstName: joi.string().required(),
lastName: joi.string().required(),
phoneNumber: joi.string().required(),
zipCode: joi.string().required()
}),
order: joi.array().items(joi.object().required().keys({
material: joi.object().required(),
options: joi.object().required().keys({
checked: joi.boolean().required(),
color: joi.string().required(),
laserMarking: joi.boolean().required(),
length: joi.string().required(),
orderQty: joi.string().required(),
type: joi.string().required()
})
})).required(),
orderObjects: joi.array().items(joi.object().required().keys({
geometries: joi.array().required(),
materials: joi.array().required(),
metadata: joi.object().required(),
object: joi.object().required()
}))
}).required(), 'Returns order object.')
.summary('Check order by key and hash')
.description('Returns order data from db.');
/**
* POST /project-rename
*/
router.post('/project-rename', function (req, res) {
try {
const user = users.document(req.session.uid);
const key = req.body.key;
const title = req.body.title;
// AQL
const result = db._query(aql`
FOR project IN OUTBOUND ${user._id} ${projectRelation}
FILTER project._key == ${key}
UPDATE project WITH { title: ${title} } IN ${projects}
LET newProject = NEW
RETURN newProject.title
`);
res.send(...result);
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.body({
key: joi.string().required(),
title: joi.string().required()
},
['application/json']
)
.response(joi.string().required(), 'Returns new project title.')
.summary('Rename project.')
.description('Rename project.');
/**
* POST /snapshot-rename
*/
router.post('/snapshot-rename', function (req, res) {
try {
const key = req.body.key;
const title = req.body.title;
const result = db._query(aql`
FOR snapshot IN ${snapshots}
FILTER snapshot._key == ${key}
UPDATE snapshot WITH { title: ${title} } IN ${snapshots}
LET newSnapshot = NEW
LET objs = (FOR items IN objects
FILTER items.snapshotKey == newSnapshot._key
RETURN {
_key: items._key,
title: items.title,
createdBy: items.createdBy,
createdAt: items.createdAt
}
)
RETURN {_key: newSnapshot._key,
_id: newSnapshot._id,
_rev: newSnapshot._rev,
title: newSnapshot.title,
createdAt: newSnapshot.createdAt,
createdBy: newSnapshot.createdBy,
objects: objs
}
`);
res.send(...result);
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.body({
key: joi.string().required(),
title: joi.string().required()
},
['application/json']
)
.response(joi.object().required().keys({
_rev: joi.string().required(),
_key: joi.string().required(),
_id: joi.string().required(),
title: joi.string().required(),
createdBy: joi.string().required(),
createdAt: joi.string().required(),
objects: joi.array().items(joi.object().required().keys({
createdAt: joi.string().required(),
createdBy: joi.string().required(),
title: joi.string().required(),
_key: joi.string().required()
}))
}), 'Return rename snapshot.')
.summary('Rename snapshot.')
.description('Rename snapshot.');