forked from Matterwiki/Matterwiki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopics.js
executable file
·117 lines (102 loc) · 3.05 KB
/
topics.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
107
108
109
110
111
112
113
114
115
116
117
/*
This file contains all the endpoints related to topics.
For the method we use to categorize endpoints in file please read the top
comment in the articles.js (same directory).
*/
// Importing the topics model
var Topics = require('../models/topic.js');
var db = require('../db.js'); //this file contains the knex file import. it's equal to knex=require('knex')
module.exports = function(app) {
app.get('/topics',function(req,res){
/*
This is a GET endpoint that responds with the list of all the topics in the topics table
the topics are present in the data object in the returning object.
the error key in the returning object is a boolen which is false if there is no error and true otherwise
*/
Topics.forge()
.fetchAll()
.then(function (collection) {
res.json({
error: {
error: false,
message: ''
},
code: 'B123',
data: collection.toJSON()
});
})
.catch(function (error) {
res.status(500).json({
error: {
error: true,
message: error.message
},
code: 'B124',
data: {
}
});
});
});
app.get('/topics/:id',function(req,res){
/*
This is a GET endpoint that responds with the topic which has the given ID
the topic is present in the data object in the returning object.
the error key in the returning object is a boolen which is false if there is no error and true otherwise
*/
Topics.forge({id: req.params.id})
.fetch()
.then(function (topic) {
res.json({
error: {
error: false,
message: ''
},
code: 'B123',
data: topic.toJSON()
});
})
.catch(function (error) {
res.status(500).json({
error: {
error: true,
message: error.message
},
code: 'B124',
data: {
}
});
});
});
app.get('/topic/:id/articles',function(req,res){
/*
This is a GET endpoint that responds with the list of all the articles that belong to a particular topic (topic of given id param)
the articles are present in the data object in the returning object.
the error key in the returning object is a boolen which is false if there is no error and true otherwise
*/
Topics.where({id: req.params.id}).fetch({withRelated: [{'articles': function(qb) {
if(req.query.count)
qb.limit(req.query.count);
qb.orderBy("updated_at","DESC");
}}]}).then(function(topic) {
res.status(200).json({
error: {
error: false,
message: ''
},
code: 'B129',
data: topic.related('articles')
});
})
.catch(function(error){
res.status(500).json({
error: {
error: true,
message: error.message
},
code: 'B130',
data: {
}
})
});
});
}