上一篇藕畔,我們講解了如何使用
jaguar_serializer
,今天变汪,我們來學習一下如何通過該package
,并結(jié)合之前的東西,封裝起RestfulApi
碱妆,該封裝同樣也適合Flutter
,dart web
閱讀該文章之前辛馆,我會默認的認為你已經(jīng)看過我之前的文章,并知道如何使用數(shù)據(jù)庫百宇,開啟服務器等考廉!
1.定義規(guī)范
- 資源
使用JSON
的形式表現(xiàn) - 資源格式
code
表示狀態(tài),0
表示處理成功,-1
表示處理失敗
msg
表示消息携御,對客戶端需要說明的一些信息昌粤,如:成功
,請求方法不允許
等
data
表示數(shù)據(jù),返回客戶端的數(shù)據(jù) - 接口
get
獲取資源啄刹,查詢資源
post
新建資源涮坐,更新資源,查詢資源
put
更新資源
delete
刪除資源 - URI
請求的地址可以附帶id等誓军,例如: Get http://localhost:8080/user/123 查詢id為123的用戶,Get http://localhost/user 查詢所有用戶, Post http://localhost:8080/user/123 修改id為123的的用戶等
2. 定義Restful
我們新建一個Restful文件,輸入下面代碼
class Restful {
int code;
String msg;
Object data;
}
然后導入jaguar_serializer
包膊升,添加下面代碼
@GenSerializer()
class RestfulSerializer extends Serializer<Restful> with _$RestfulSerializer {}
運行命令pub run build_runner build
,完后繼續(xù)添加
part 'Restful.jser.dart';
ok谭企,我們已經(jīng)準備好Restful廓译,那怎么把數(shù)據(jù)放到data里面呢
我們先來創(chuàng)建一個user.dart
文件评肆,創(chuàng)建一個用戶模型,
class User {
String id;
String username;
String password;
int role;
String phoneNumber;
int sex;
}
與數(shù)據(jù)庫進行關聯(lián)
import 'package:jaguar_orm/jaguar_orm.dart';
import 'dart:async';
part 'user.jorm.dart';
class User {
@PrimaryKey()
String id;
String username;
String password;
int role;
@Column(length: 11)
String phoneNumber;
int sex;
static const String tableName='_user';
@override
String toString()=> 'User(id:$id,username:$username,password:$password,role:$role,phoneNumber:$phoneNumber,sex:$sex)';
}
@GenBean()
class UserBean extends Bean<User> with _UserBean {
UserBean(Adapter adapter) : super(adapter);
@override
String get tableName => User.tableName;
}
創(chuàng)建一個serializer.dart
文件,用于存放所有json_serializer
工具文件非区,添加下面代碼
import 'package:jaguar_serializer/jaguar_serializer.dart';
import 'user.dart';
part 'serializer.jser.dart';
@GenSerializer()
class UserSerializer extends Serializer<User> with _$UserSerializer {
}
運行pub run build_runner build
命令
下面是打印一個通過數(shù)據(jù)庫查詢id
為2的restful api
返回數(shù)據(jù)
import 'package:jaguar_query_postgres/jaguar_query_postgres.dart';
import 'package:TestDB/user.dart';
import 'package:TestDB/Restful.dart';
import 'package:TestDB/serializer.dart';
import 'dart:convert';
final PgAdapter pgAdapter =
new PgAdapter('postgres', username: 'postgres', password: '123456');
main() async {
await pgAdapter.connect();
Restful restful = new Restful()
..code = 0
..msg = 'success'
..data = new UserSerializer().toMap((await new UserBean(pgAdapter).find("2")));
print(json.encode(new RestfulSerializer().toMap(restful)));
}
我們可以簡單的知道瓜挽,一個模型轉(zhuǎn)換為json數(shù)據(jù)需要經(jīng)過兩步操作
-
模型
轉(zhuǎn)換為Map
-
map
經(jīng)過json.encode
編碼為字符串
相反的,json數(shù)據(jù)轉(zhuǎn)換為模型也是兩步
-
字符串
經(jīng)過json.decode
譯碼為map
-
map
轉(zhuǎn)換為模型
所以征绸,我們可以結(jié)合jaguar_serializer
封裝一下Restful久橙,封裝如下
import 'dart:convert';
import 'package:jaguar_serializer/jaguar_serializer.dart';
part 'Restful.jser.dart';
RestfulSerializer serializer = new RestfulSerializer();
class Restful {
int code;
String msg;
Object data;
Restful();
Map toMap([Serializer dataSerializer]) {
if(dataSerializer==null){
return serializer.toMap(this);
}
if (data is List) {
List list =data;
if(list.length!=0&& list[0] is Map){
}else if(list.length!=0){
data = dataSerializer.toList(data);
}
} else if (data is Map) {
} else {
data = dataSerializer.toMap(data);
}
return serializer.toMap(this);
}
String toJson([Serializer dataSerializer]) {
return json.encode(toMap(dataSerializer));
}
factory Restful.fromMap(Map<String,dynamic> map, [Serializer dataSerializer]) {
Restful api = serializer.fromMap(map);
if(dataSerializer==null){
return api;
}
if (api.data is List) {
List<Map<dynamic,dynamic>> data=(api.data as List<dynamic>).map((d)=>d as Map<dynamic,dynamic>).toList();
api.data = dataSerializer.fromList(data);
} else if (api.data == null) {
} else {
api.data = dataSerializer.fromMap(api.data);
}
return api;
}
factory Restful.fromJson(String Json, [Serializer dataSerializer]) {
return new Restful.fromMap(json.decode(Json),dataSerializer);
}
T fromJsonToData<T>(String Json,Serializer dataSerializer) {
Restful api = serializer.fromMap(json.decode(Json));
if (api.data is List) {
// throw ArgumentError('data is List');
return null;
} else if (api.data == null) {
return null;
} else {
return dataSerializer.fromMap(api.data);
}
}
List<T> fromJsonToListData<T>(String Json, [Serializer dataSerializer]) {
Restful restful = new Restful.fromJson(Json, dataSerializer);
if (restful.data is List) {
if(dataSerializer==null){
return restful.data;
}
return restful.data;
} else if (restful.data == null) {
return null;
} else {
return null;
}
}
}
@GenSerializer()
class RestfulSerializer extends Serializer<Restful> with _$RestfulSerializer {}
上面主要有6個方法
-
toMap([Serializer dataSerializer])
將Restful
轉(zhuǎn)換為map
,傳入的是data對應的類型序列化工具[]
表示非必填管怠,如果data
是基本類型淆衷,可不填 -
toJson([Serializer dataSerializer])
將Restful
轉(zhuǎn)換為字符串
-
Restful.fromMap(Map<String,dynamic> map, [Serializer dataSerializer])
將map
轉(zhuǎn)換為Restful
-
Restful.fromJson(String Json, [Serializer dataSerializer])
將字符串
轉(zhuǎn)換為Restful
-
fromJsonToData<T>(String Json,Serializer dataSerializer)
將字符串
直接轉(zhuǎn)換為data
(T
為泛型) -
fromJsonToListData<T>(String Json, [Serializer dataSerializer])
將字符串
直接轉(zhuǎn)換為List<T>
3.定制接口
工具已經(jīng)有了,數(shù)據(jù)也有了渤弛,那么我們現(xiàn)在就開始著手寫接口了
main.dart
import 'package:jaguar_query_postgres/jaguar_query_postgres.dart';
import 'package:jaguar/jaguar.dart';
import 'package:jaguar_reflect/jaguar_reflect.dart';
import 'package:TestDB/UserController.dart';
final PgAdapter pgAdapter =
new PgAdapter('postgres', username: 'postgres', password: '123456');
main() async {
await pgAdapter.connect();
new Jaguar( port: 1000)
..add(reflect(new UserController(pgAdapter)))
..serve();
}
UserController.dart
import 'package:jaguar/jaguar.dart';
import 'package:jaguar_orm/jaguar_orm.dart';
import 'serializer.dart';
import 'Restful.dart';
import 'user.dart';
@Controller(path: '/user')
class UserController {
final UserBean userBean;
UserController(Adapter adapter):userBean=new UserBean(adapter);
@Get( path: '/:id')
user(Context ctx) async{
String id=ctx.pathParams['id'];
Restful restful=new Restful()
..code=0
..msg='success'
..data=await userBean.find(id);
return Response.json( restful.toMap(new UserSerializer()));
}
}
我們來請求一下數(shù)據(jù)看看http://localhost:1000/user/1
可以看到祝拯,我們成功的在數(shù)據(jù)庫中查找到一條記錄,然后以json的形式傳遞給客戶端
下面就是寫其他的增刪查改接口了
import 'package:jaguar/jaguar.dart';
import 'package:jaguar_orm/jaguar_orm.dart';
import 'serializer.dart';
import 'Restful.dart';
import 'user.dart';
@Controller(path: '/user')
class UserController {
final UserBean userBean;
UserController(Adapter adapter):userBean=new UserBean(adapter);
@Get( path: '/:id')
user(Context ctx) async{
String id=ctx.pathParams['id'];
Restful restful=new Restful()
..code=0
..msg='success'
..data=await userBean.find(id);
return Response.json( restful.toMap(new UserSerializer()));
}
@Post(path: '/:id')
userEdit(Context ctx) async{
String id=ctx.pathParams['id'];
User user=await ctx.bodyAsJson(convert: new UserSerializer().fromMap);
user.id=id;
await userBean.update(user);
return Response.json((new Restful()
..code=0
..msg='ok').toMap());
}
@Put(path: '/')
userAdd(Context ctx) async{
User user=await ctx.bodyAsJson(convert: new UserSerializer().fromMap);
await userBean.insert(user);
return Response.json((new Restful()
..code=0
..msg='ok').toMap());
}
@Delete(path: '/:id')
userDelete(Context ctx) async{
String id=ctx.pathParams['id'];
await userBean.remove(id);
return Response.json((new Restful()
..code=0
..msg='ok').toMap());
}
}
ok,上面就是今天的全部內(nèi)容她肯,我們明天見!
如果想繼續(xù)學習DartVM服務器開發(fā)佳头,請關注我,學習更多騷操作晴氨!