-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroutes.py
More file actions
305 lines (239 loc) · 8.75 KB
/
routes.py
File metadata and controls
305 lines (239 loc) · 8.75 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
import logging
from flask import Response, jsonify, request
from werkzeug.exceptions import BadRequest
from db import base62
from db.flask import (
count_nodes,
count_tags,
create_node,
create_tag,
delete_node,
delete_tag,
fetch_children,
fetch_node,
fetch_nodes_for_tag,
fetch_nodes_page,
fetch_parent_id,
fetch_tag,
fetch_tags_for_node,
fetch_tags_page,
node_row_to_dict,
tag_row_to_dict,
update_node,
update_tag,
)
from web import error
logger = logging.getLogger(__name__)
def _decode_id(raw: str, name: str) -> int:
try:
return base62.decode(raw)
except (TypeError, ValueError):
raise BadRequest(f'invalid {name}: {raw!r}')
def _parse_json_body() -> dict:
"""Return parsed JSON body, or raise 400 on malformed JSON / missing body."""
data = request.get_json(force=True, silent=False)
if data is None:
raise BadRequest('Request body must be valid JSON')
return data
# Tag endpoints
def get_tags_list() -> Response:
try:
limit = int(request.args.get('limit', 100))
offset = int(request.args.get('offset', 0))
except ValueError:
return error(400, 'limit and offset must be integers')
if limit < 1 or limit > 1000:
return error(400, 'limit must be between 1 and 1000')
if offset < 0:
return error(400, 'offset must be non-negative')
total = count_tags()
rows = fetch_tags_page(limit, offset)
return jsonify(
{
'total': total,
'limit': limit,
'offset': offset,
'items': [tag_row_to_dict(r) for r in rows],
}
)
def get_tag_detail(tag_id: str) -> Response:
tag_id_int = _decode_id(tag_id, 'tag_id')
tag = fetch_tag(tag_id_int)
if not tag:
return error(404, 'Tag not found')
nodes = fetch_nodes_for_tag(tag_id_int)
return jsonify(
{
**tag_row_to_dict(tag),
'nodes': [node_row_to_dict(n) for n in nodes],
}
)
def post_tag_create() -> Response:
data = _parse_json_body()
name = data['name']
try:
tag_id = create_tag(name)
except ValueError as e:
return error(409, str(e))
tag = fetch_tag(tag_id)
if tag is None:
logger.error('fetch_tag returned None after create_tag succeeded for name=%r', name)
return error(500, 'Internal server error')
resp = jsonify(tag_row_to_dict(tag))
resp.status_code = 201
return resp
def delete_tag_endpoint(tag_id: str) -> Response:
delete_op = delete_tag(_decode_id(tag_id, 'tag_id'))
if delete_op is None:
return error(404, 'Tag not found')
total, node_count = delete_op
return jsonify({'deleted': {'total': total, 'associations': node_count}})
def patch_tag_update(tag_id: str) -> Response:
tag_id_int = _decode_id(tag_id, 'tag_id')
data = _parse_json_body()
name = data['name']
try:
rowcount = update_tag(tag_id_int, name)
except ValueError as e:
return error(409, str(e))
if rowcount == 0:
return error(404, 'Tag not found')
tag = fetch_tag(tag_id_int)
if tag is None:
logger.error('fetch_tag returned None after update_tag succeeded for tag_id=%s', tag_id)
return error(500, 'Internal server error')
return jsonify(tag_row_to_dict(tag))
# Node endpoints
def get_nodes_list() -> Response:
try:
limit = int(request.args.get('limit', 100))
offset = int(request.args.get('offset', 0))
except ValueError:
return error(400, 'limit and offset must be integers')
if limit < 1 or limit > 1000:
return error(400, 'limit must be between 1 and 1000')
if offset < 0:
return error(400, 'offset must be non-negative')
total = count_nodes()
rows = fetch_nodes_page(limit, offset)
return jsonify({'total': total, 'limit': limit, 'offset': offset, 'items': [node_row_to_dict(r) for r in rows]})
def get_node_detail(node_id: str) -> Response:
node_id_int = _decode_id(node_id, 'node_id')
row = fetch_node(node_id_int)
if not row:
return error(404, 'Node not found')
parent_id_int = fetch_parent_id(node_id_int)
children = fetch_children(node_id_int)
tags = fetch_tags_for_node(node_id_int)
node = node_row_to_dict(row)
node['parent_id'] = base62.encode(parent_id_int) if parent_id_int is not None else None
node['children'] = children
node['tags'] = tags
return jsonify(node)
def post_node_create() -> Response:
data = _parse_json_body()
label = data.get('label')
if label is None:
return error(400, 'Missing required field: label')
if not label:
return error(400, 'Required field cannot be empty: label')
if len(label) > 255:
return error(400, 'label must be 255 characters or fewer')
description = data.get('description')
if description == '':
return error(400, 'description cannot be empty')
is_container = bool(data.get('is_container', False))
raw_parent_id = data.get('parent_id')
raw_tag_ids = data.get('tag_ids') or []
try:
parent_id_int = _decode_id(raw_parent_id, 'parent_id') if raw_parent_id is not None else None
tag_id_ints = [_decode_id(t, 'tag_ids') for t in raw_tag_ids]
except BadRequest as e:
return error(400, e.description)
try:
node_id = create_node(label, description, is_container, parent_id=parent_id_int, tag_ids=tag_id_ints)
except ValueError as ve:
logger.error(f'Validation error in post_node_create: {ve}')
return error(400, str(ve))
# Fetch full node representation
row = fetch_node(node_id)
if row is None:
logger.error('fetch_node returned None after create_node succeeded for node_id=%d', node_id)
return error(500, 'Internal server error')
parent_id_int = fetch_parent_id(node_id)
children = fetch_children(node_id)
tags = fetch_tags_for_node(node_id)
node = node_row_to_dict(row)
node['parent_id'] = base62.encode(parent_id_int) if parent_id_int is not None else None
node['children'] = children
node['tags'] = tags
resp = jsonify(node)
resp.status_code = 201
return resp
def patch_node_update(node_id: str) -> Response:
node_id_int = _decode_id(node_id, 'node_id')
data = _parse_json_body()
fields = {}
if 'label' in data:
if not data['label']:
return error(400, 'label cannot be empty')
if len(data['label']) > 255:
return error(400, 'label must be 255 characters or fewer')
fields['label'] = data['label']
if 'description' in data:
if data['description'] == '':
return error(400, 'description cannot be empty')
fields['description'] = data['description']
if 'is_container' in data:
fields['is_container'] = bool(data['is_container'])
parent_provided = 'parent_id' in data
raw_parent_id = data.get('parent_id') if parent_provided else None
tag_ids_provided = 'tag_ids' in data
raw_tag_ids = data.get('tag_ids') or []
try:
parent_id_int = _decode_id(raw_parent_id, 'parent_id') if raw_parent_id is not None else None
tag_id_ints = [_decode_id(t, 'tag_ids') for t in raw_tag_ids]
except BadRequest as e:
return error(400, e.description)
try:
found = update_node(
node_id_int,
fields,
parent_provided=parent_provided,
parent_id=parent_id_int,
tag_ids_provided=tag_ids_provided,
tag_ids=tag_id_ints,
)
except ValueError as ve:
logger.error(f'Validation error in patch_node_update for node {node_id}: {ve}')
return error(400, str(ve))
if not found:
return error(404, 'Node not found')
# Return updated representation
row = fetch_node(node_id_int)
if row is None:
logger.error('fetch_node returned None after update succeeded for node_id=%d', node_id_int)
return error(500, 'Internal server error')
parent_id_int = fetch_parent_id(node_id_int)
children = fetch_children(node_id_int)
tags = fetch_tags_for_node(node_id_int)
node = node_row_to_dict(row)
node['parent_id'] = base62.encode(parent_id_int) if parent_id_int is not None else None
node['children'] = children
node['tags'] = tags
return jsonify(node)
def delete_node_endpoint(node_id: str) -> Response:
delete_op = delete_node(_decode_id(node_id, 'node_id'))
if delete_op is None:
return error(404, 'Node not found')
object_count, edge_count, tag_count, node_count = delete_op
return jsonify(
{
'deleted': {
'total': object_count,
'edges': edge_count,
'tags': tag_count,
'nodes': node_count,
},
}
)