struct MyTest: Content {
let hello: String
}
// http://127.0.0.1:8080/test-send
app.get("test-send") { req -> EventLoopFuture<Response> in
let info = MyTest.init(hello: "World")
let infoData = try! JSONEncoder().encode(info)
let infoString = String(data: infoData, encoding: .utf8)
let inputJsonDic = ["hello": "world"]
return req.client.post("http://127.0.0.1:8080/test-receive") { clientReq in
// Value of type 'Dictionary<String, Any>' required for key ''. [request-id: 8236FDDD-B57C-4F86-8114-282A762E0B41]
try clientReq.content.encode(infoString, as: .json)
// can work
// try clientReq.content.encode(inputJsonDic)
}
.flatMap { json in
return json.encodeResponse(for: req)
}
}
app.post("test-receive") { req -> MyTest in
let info = try req.content.decode(MyTest.self)
return info
}
Make MyTest
conform to Content
then do
return req.client.post("http://127.0.0.1:8080/test-receive") { clientReq in
try clientReq.content.encode(info)
}
I receive data from other services and am not sure about model properties.
How to solve this? After configuring .json
, the Decode model cannot be correct. Is there any special treatment?
If you want to set the data directly you can set it on the request ByteBuffer
body using one of NIO's convenience functions, or directly
This works, but I don’t know if their results are consistent.
return req.client.post("\(AppConfig.environment.backend_callbackUrl)") { clientReq in
// // Encode query string to the request URL.
// try clientReq.query.encode(["q": "test"])
//
// Encode JSON to the request body.
// try clientReq.content.encode(["hello": "world"])
clientReq.headers.contentType = .json
clientReq.body = .init(string: jsonString)
//
// // Add auth header to the request
// let auth = BasicAuthorization(username: "something", password: "somethingelse")
// clientReq.headers.basicAuthorization = auth
}
// .flatMapThrowing { clientRes in
// try clientRes.content.decode(MyJSONResponse.self)
// }
.flatMap { json in
return json.encodeResponse(for: req)
}
What do you mean you don't know if it's consistent?
try clientReq.content.encode(["hello": "world"])
vs
clientReq.headers.contentType = .json
clientReq.body = .init(string: #"{"hello": "world"}"#)
Are they the same?
Honestly I'm not 100% sure - just try it and see