handlePatch method Null safety
- Request request
Handles Patch http requisitions. Requires a http Request (from the Shelf package).
Implementation
Future<Response> handlePatch(Request request) async {
if (!middlewareJwt(request)) {
return Response.forbidden(jsonEncode({'error': 'middlewareJwt'}));
}
try {
final content = await request.readAsString(); /*2*/
final data = jsonDecode(content) as Map;
final key = request.url.pathSegments[0];
final dynamic seg = await config.db.getAll(key);
if (seg == null) {
return Response.notFound(jsonEncode({'error': 'Not found'}));
} else {
data['id'] = int.parse(request.url.pathSegments[1]);
final position = (seg as List).indexWhere(
(element) => element['id'] == int.parse(request.url.pathSegments[1]),
);
data.forEach((key, value) {
seg[position][key] = value;
});
await config.db.save(key, seg);
return Response.ok(
jsonEncode(data),
headers: {'content-type': 'application/json'},
);
}
} catch (e) {
return Response.internalServerError(
body: jsonEncode({'error': 'Internal Error'}),
);
}
}