Implemented saving data as JSON object to a file.
This commit is contained in:
parent
0ed3f745ae
commit
d8f8aec75d
2 changed files with 33 additions and 0 deletions
|
@ -3,6 +3,7 @@ library titama.server;
|
|||
import 'package:rpc/rpc.dart';
|
||||
|
||||
import '../common/messages.dart';
|
||||
import './titamaio.dart';
|
||||
|
||||
@ApiClass(version: 'v1')
|
||||
class TitamaApi {
|
||||
|
@ -56,6 +57,9 @@ class TitamaApi {
|
|||
@ApiMethod(method: 'DELETE', path: 'course/{id}')
|
||||
List<Course> deleteCourse(int id) {
|
||||
_courses.removeWhere((course) => course.id == id);
|
||||
|
||||
new TitamaIo().writeJson(_courses);
|
||||
|
||||
return _courses;
|
||||
}
|
||||
|
||||
|
@ -64,6 +68,8 @@ class TitamaApi {
|
|||
newCourse.id = _courses.length;
|
||||
_courses.add(newCourse);
|
||||
|
||||
new TitamaIo().writeJson(_courses);
|
||||
|
||||
return newCourse;
|
||||
}
|
||||
|
||||
|
@ -72,6 +78,9 @@ class TitamaApi {
|
|||
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;
|
||||
}
|
||||
}
|
||||
|
|
24
lib/server/titamaio.dart
Normal file
24
lib/server/titamaio.dart
Normal 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);
|
||||
}
|
||||
|
||||
}
|
Reference in a new issue