Implemented saving data as JSON object to a file.

This commit is contained in:
Marcel Kapfer (mmk2410) 2016-06-25 10:44:10 +02:00
parent 0ed3f745ae
commit d8f8aec75d
2 changed files with 33 additions and 0 deletions

View file

@ -3,6 +3,7 @@ library titama.server;
import 'package:rpc/rpc.dart'; import 'package:rpc/rpc.dart';
import '../common/messages.dart'; import '../common/messages.dart';
import './titamaio.dart';
@ApiClass(version: 'v1') @ApiClass(version: 'v1')
class TitamaApi { class TitamaApi {
@ -56,6 +57,9 @@ class TitamaApi {
@ApiMethod(method: 'DELETE', path: 'course/{id}') @ApiMethod(method: 'DELETE', path: 'course/{id}')
List<Course> deleteCourse(int id) { List<Course> deleteCourse(int id) {
_courses.removeWhere((course) => course.id == id); _courses.removeWhere((course) => course.id == id);
new TitamaIo().writeJson(_courses);
return _courses; return _courses;
} }
@ -64,6 +68,8 @@ class TitamaApi {
newCourse.id = _courses.length; newCourse.id = _courses.length;
_courses.add(newCourse); _courses.add(newCourse);
new TitamaIo().writeJson(_courses);
return newCourse; return newCourse;
} }
@ -72,6 +78,9 @@ class TitamaApi {
course.id = id; course.id = id;
int index = _courses.indexOf(_courses.singleWhere((crs) => crs.id == id)); int index = _courses.indexOf(_courses.singleWhere((crs) => crs.id == id));
_courses.replaceRange(index, index + 1, [course]); _courses.replaceRange(index, index + 1, [course]);
new TitamaIo().writeJson(_courses);
return course; return course;
} }
} }

24
lib/server/titamaio.dart Normal file
View file

@ -0,0 +1,24 @@
library titama.io;
import 'dart:io';
import 'dart:convert';
import '../common/messages.dart';
/**
* Class for writing and loading the courses as JSON to a file.
*/
class TitamaIo {
final _filename = "./data.json";
/**
* Write courses as JSON in a file.k
* @param List<Courses> _course List of courses to save.
*/
writeJson(List<Course> _courses) async {
String _json = JSON.encode(_courses);
await new File(_filename).writeAsString(_json);
}
}