postJSON method
- RequestData rd
post_JSON to our backend as the user
Implementation
Future<http.BaseResponse?> postJSON(RequestData rd) async {
var headers = {HttpHeaders.contentTypeHeader: 'application/json'};
rd.json = rd.json ?? {};
rd.json!['user'] = _user?.toJson();
try {
if (rd.multipartFiles.isNotEmpty) {
http.MultipartRequest? mreq;
try {
var fullURL = Uri.parse(_baseurl + rd.route);
mreq = http.MultipartRequest('POST', fullURL)
..files.addAll(
List<http.MultipartFile>.from((await Future.wait(
rd.multipartFiles.map(
(fxfile) async {
final xfile = await fxfile;
final name = xfile.name;
var creation = 0;
creation = FileStat.statSync(xfile.path)
.changed
.toUtc()
.millisecondsSinceEpoch;
final path = xfile.path;
return http.MultipartFile.fromPath(
creation.toString(), path,
filename: name);
},
),
))
.whereType<http.MultipartFile>()),
)
..headers.addAll({HttpHeaders.authorizationHeader: _api_key})
..fields.addAll(/*flatten()*/ rd.json!.map<String, String>(
(key, value) => MapEntry(
key,
value
.toString()))); // this causes #279, but that is fixed in backend, since the formrequests fields is Map<String, String> and not Map<String, dynamic>
debugPrint("gonna send multipart-req with booty ${mreq.fields}");
var res = (rd.timeout == null)
? await mreq.send()
: await mreq.send().timeout(rd.timeout!);
return res;
} on Exception catch (e) {
//if (rd.////logIfFailed) OP.logFailedReq(rd);
debugPrint('multipartRequest, failed');
throw e;
}
} else {
final req =
makepost(rd.route, headers: headers, body: jsonEncode(rd.json));
try {
return await send(
req,
timeout: rd.timeout,
returnsBinary: rd.returnsBinary,
);
} catch (e) {
//if (rd.////logIfFailed) OP.logFailedReq(rd);
//debugPrint('request failed');
throw e;
}
}
} catch (e) {
//debugPrint("request failed, cause : $e");
return null;
}
}