This repository has been archived on 2022-02-10. You can view files and clone it, but cannot push or open issues or pull requests.
titama-backend/lib/server/titamaapi.dart
2016-07-17 23:41:24 +02:00

65 lines
1.4 KiB
Dart

library titama.server;
import 'package:rpc/rpc.dart';
import '../common/messages.dart';
import './titamaio.dart';
@ApiClass(version: 'v1')
class TitamaApi {
List<Course> _courses = new List<Course>();
TitamaApi(List<Course> courses) {
// assign saved courses to list
_courses = courses;
}
@ApiMethod(path: 'courses')
List<Course> listCourses() {
if (_courses.isEmpty) {
throw new NotFoundError('Could not find any courses.');
}
return _courses;
}
@ApiMethod(path: 'course/{id}')
Course getCourse(int id) {
for (Course course in _courses) {
if (course.id == id) {
return course;
}
}
throw new NotFoundError('Could not find course \'$id\'.');
}
@ApiMethod(method: 'DELETE', path: 'course/{id}')
List<Course> deleteCourse(int id) {
_courses.removeWhere((course) => course.id == id);
new TitamaIo().writeJson(_courses);
return _courses;
}
@ApiMethod(method: 'POST', path: 'course')
Course addCourse (Course newCourse) {
newCourse.id = _courses.length;
_courses.add(newCourse);
new TitamaIo().writeJson(_courses);
return newCourse;
}
@ApiMethod(method: 'PUT', path: 'course/{id}')
Course updateCourse(int id, Course course) {
course.id = id;
int index = _courses.indexOf(_courses.singleWhere((crs) => crs.id == id));
_courses.replaceRange(index, index + 1, [course]);
new TitamaIo().writeJson(_courses);
return course;
}
}