Firebase云函数-对象不能在JSON-Kotlin数据类中编码



目前,我正在尝试在我的android应用程序中调用https firebase云函数。我遇到的唯一问题是,当我试图用一些数据调用函数时,我会得到错误:

"对象不能用JSON编码";。

我的问题是:我该如何解决这个问题?我试图传递的对象是一个kotlin数据类。我必须先手动将数据转换为json对象(使用gson(还是有更好的解决方案?

这是我目前的解决方案:(不工作,出现内部错误(

数据类

data class UserDeliveryAddress(
val company: String? = "",
val fullName: String = "",
val postcode: Int = 0,
val city: String = "",
val street: String = "",
val houseNumber: Int = 0,
val country: String = "",
)

用法

if (optionalAdress != null) {
val data = gson.toJson(userDeliveryNetworkEntityMapper.mapToEntity(optionalAdress))
dbFunctions.getHttpsCallable("authOnCreate")
.call(data) // just getting "internal" error
.await()
}

Cloud函数

export async function doOnAuthCreate(data: any, context: functions.https.CallableContext) {
functions.logger.info("AUTH ON CREATE - Creating new user");
const dataObject = JSON.parse(data);

functions.logger.info(`Country is: ${dataObject.country}`);
functions.logger.info("AUTH ON CREATE - Sucessfully created user");
return 0;
}

索引.ts

import { doOnAuthCreate } from "./auth/onCreate.f"
export const authOnCreate = functions
.region(region)
.https
.onCall(doOnAuthCreate);

好吧,我已经设法解决了这个问题,下面是解决方案:

用法

optionalAdress?.let {
val mappedAdress = userDeliveryNetworkEntityMapper.mapToEntity(it).asHashMap(gson = gson)
dbFunctions.getHttpsCallable("authOnCreate")
.call(mappedAdress)
.await()
}

转换数据类

fun <T> T.asHashMap(gson: Gson): HashMap<String, Any> {
return convert(gson)
}
private inline fun <I, reified O> I.convert(gson: Gson): O {
val json = gson.toJson(this)
return gson.fromJson(json, object : TypeToken<O>() {}.type)
}

Cloud函数

export async function doOnAuthCreate(data: any) {
functions.logger.info("AUTH ON CREATE - Creating new user");
const company = data.company;
functions.logger.info(`AUTH ON CREATE - Company is ${company}`)
functions.logger.info("AUTH ON CREATE - Sucessfully created user");
}

index.ts

export const authOnCreate = functions
.region(region)
.https
.onCall(doOnAuthCreate);

如果想要将https函数与firebase函数模拟器结合使用,则必须将以下内容添加到app.onCreate((和清单中:

应用程序

class App : Application() {
override fun onCreate() {
initOnTest()
}
}
private fun initOnTest() {
val fireStore = Firebase.firestore
fireStore.useEmulator("10.0.2.2", 8080)
val fireFunctions = Firebase.functions
fireFunctions.useEmulator("10.0.2.2", 5001)
val fireAuth = Firebase.auth
fireAuth.useEmulator("10.0.2.2", 9099)
val settings = FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(false)
.build()
fireStore.firestoreSettings = settings
}

清单(禁止在生产中使用!!!!(

<application
android:usesCleartextTraffic="true"

相关内容

  • 没有找到相关文章