danfma
04/06/2017, 6:52 PMclass SignUpService(val jsonService: HttpJsonService = HttpJsonService()) {
fun signUp(data: SignUp): Future<SignUpResponse> {
return jsonService.sendPost<SignUpResponse>(
"~/api/account/signup",
SignUpRequest.from(data)
)
}
}
open class HttpJsonService {
protected open fun <T> unwrap(response: Response): Future<T> =
async {
when (response.status) {
200.toShort(),
201.toShort() -> {
val data: T = await(response.json().unsafeCast<Promise<T>>())
data
}
400.toShort() -> {
val validation = await(response.json().unsafeCast<Promise<IValidationResult?>>())
if (validation != null)
throw ValidationException(validation)
else
throw ServerException(response)
}
else -> {
throw ServerException(response)
}
}
}
fun <T> sendGet(url: String, params: Map<String, Any>? = null) =
async {
val mappedUrl = Url.mapUrl(url, params)
val response = await(fetch(mappedUrl))
await(unwrap<T>(response))
}
fun <T> sendPost(url: String, data: Any?, params: Map<String, Any>? = null): Future<T> =
async {
val mappedUrl = Url.mapUrl(url, params)
val request = FetchRequestInit(
method = “POST”,
headers = json(
“Content-Type” to “application/json”
),
body = if (data != null) JSON.stringify(data) else undefined)
val response = await(fetch(mappedUrl, request))
await(unwrap<T>(response))
}
}