Skip to content

Instantly share code, notes, and snippets.

@ThomasLocke
Created September 29, 2014 14:00
Show Gist options
  • Save ThomasLocke/0ac5dca046c00ce25f49 to your computer and use it in GitHub Desktop.
Save ThomasLocke/0ac5dca046c00ce25f49 to your computer and use it in GitHub Desktop.
shelftest.handlers.dart
library shelftest.handlers;
import 'dart:async';
import 'dart:convert';
import 'dart:io' show HttpHeaders;
import 'database.dart';
import 'user.dart';
import 'package:shelf_exception_response/exception.dart';
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf_path/shelf_path.dart';
const Map headers = const {HttpHeaders.CONTENT_TYPE: 'application/json'};
/**
* Extract the 'name' value from the JSON decoded [body].
*
* Throw [BadRequestException] if [body] cannot decode to JSON.
*/
String _getUserName(String body) {
try {
return JSON.decode(body)['name'];
} catch (_) {
throw new BadRequestException({'error':'body malformed'});
}
}
/**
* Extract the 'userid' GET path parameter from [request].
*
* Throw [BadRequestException] if 'userid' is not an integer.
*/
int _getUserId(shelf.Request request) {
try {
return int.parse(getPathParameter(request, 'userid'));
} catch(_) {
throw new BadRequestException({'error': 'userid must be an integer'});
}
}
/**
* Return a [User] as JSON.
*
* Throw [NotFoundException] if the 'userid' GET path parameter doesn't exist.
*/
shelf.Response getUser(shelf.Request request) {
final User user = db.getUser(_getUserId(request));
if(user != null) {
return new shelf.Response.ok(JSON.encode(user), headers: headers);
} else {
throw new NotFoundException({'error': 'unknown userid'});
}
}
/**
* Set username for the 'userid' GET path parameter [User].
*
* The [request] body is expected to adhere to the following format:
*
* {"name":"Some Name"}
*
* Throw [BadRequestException] if the body is malformed. Throw [NotFoundException]
* if the 'userid' [User] doesn't exist.
*/
Future<shelf.Response> setUserName(shelf.Request request) {
return request.readAsString().then((String content) {
final int userId = _getUserId(request);
db.setUserName(userId, _getUserName(content));
return new shelf.Response.ok(JSON.encode(db.getUser(userId)), headers: headers);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment