Decoding snake case
imyrvold opened this issue · 2 comments
I am posting a request:
struct UserCreateRequest: JsonRequest {
typealias Result = User
var firstName: String
var lastName: String
var email: String
var password: String
var role: String
var routes: HttpRoute {
["users"]
}
var method: HttpMethod { .post }
var body: HttpBody {
HttpData.Json(UserCreateBody(firstName: firstName, lastName: lastName
, email: email, password: password, role: role))
}
var usesSecureProtocol: Bool {
false
}
var decodeSnakeCase: Bool {
false
}
}
The body of the request looks OK in the log, with camelcase:
[Squid] Scheduled request UserCreateRequest
with identifier 5:
[Squid] - Method: POST
[Squid] - Url: http://192.168.100.9:3000/api/v1/users
[Squid] - Headers: * Authorization => Bearer%20eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1Y2Q1NGZmYmYzM2M2NzAwMjMzMDdiZGYiLCJyb2xlIjoiNWM2YmUzYWM3MTBkYjMyYTljNzdhMTJhIiwiaWF0IjoxNTgxMTYzMjgzLCJleHAiOjE1ODExNjY4ODMsImF1ZCI6Imh0dHA6Ly9hcGkvdjEvcHJvdGVjdGVkIiwiaXNzIjoiaHR0cHM6Ly9hdml0ZWxsLm5vIiwic3ViIjoiYXZpdGVsbEBhdml0ZWxsLm5vIn0.OttzMT3fCSyNJ9BtQ9HNb-8-gWFwxPUqFSUbDNJTp97BrXIOruAIhoytgRZ00N_osPju8jMGQVdF0dEBlE-ksg
[Squid] * Content-Type => application/json
[Squid] - Body: {
[Squid] "firstName" : "Donald",
[Squid] "email" : "donald@duck.com",
[Squid] "lastName" : "Duck",
[Squid] "password" : "duckduckgo",
[Squid] "role" : "5c6be3ac710db32a9c77a12b"
[Squid] }
But what is sent is snake case:
users controller create ctx.request.body: {
email: 'donald@duck.com',
password: 'duckduckgo',
last_name: 'Duck',
first_name: 'Donald',
role: '5c6be3ac710db32a9c77a12b'
}
ValidationError: User validation failed: lastName: Path lastName
is required., firstName: Path firstName
is required.
at new ValidationError (/Users/imyrvold/development/Advantek/sdweb/backend/node_modules/mongoose/lib/error/validation.js:30:11)
at model.Document.invalidate (/Users/imyrvold/development/Advantek/sdweb/backend/node_modules/mongoose/lib/document.js:2250:32)
at p.doValidate.skipSchemaValidators (/Users/imyrvold/development/Advantek/sdweb/backend/node_modules/mongoose/lib/document.js:2099:17)
at /Users/imyrvold/development/Advantek/sdweb/backend/node_modules/mongoose/lib/schematype.js:978:9
at processTicksAndRejections (internal/process/task_queues.js:75:11)
When you set the body to HttpData.Json
, by default, a snake case encoder will be used as defined as follows:
fileprivate func snakeCaseJSONEncoder() -> JSONEncoder {
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
return encoder
}
When you do not want that behavior, pass your own JSONEncoder instance like so:
HttpData.Json(
UserCreateBody(firstName: firstName, lastName: lastName, email: email, password: password, role: role),
encoder: JSONEncoder()
)
I'll close this for now as it is not an issue with the library itself.
Actually was an issue with the library itself, fixed the printing now ... thanks for the report :)