Skip to content

Instantly share code, notes, and snippets.

@hiranya911
Created March 2, 2020 00:10
Show Gist options
  • Save hiranya911/8d1a55765706ebebe7dd5d92147cee03 to your computer and use it in GitHub Desktop.
Save hiranya911/8d1a55765706ebebe7dd5d92147cee03 to your computer and use it in GitHub Desktop.
// This version of the application code was written for the V1 schema.
const val SUPPORTED_SCHEMA_VERSION = 1
private val db = FirebaseFirestore.getInstance()
private val remoteConfig = FirebaseRemoteConfig.getInstance()
private val schemaMappings = mutableMapOf<String,JsonObject>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
remoteConfig.fetchAndActivate()
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
queryFirestore()
}
}
}
private fun queryFirestore() {
db.collection("people")
.get()
.addOnSuccessListener { snapshot ->
for (doc in snapshot.documents) {
// getField will transparently map `surname` to the correct field name.
val surname = doc.getField("surname")
displayField(surname)
}
}
}
/**
* Helper method for getting a field value from a snapshot. Transparently
* resolves the field names to their updated names in newer schema versions.
*/
private fun DocumentSnapshot.getField(field: String): Any? {
val data = this.data ?: hashMapOf()
val schemaVersion = data["v"] as? Long ?: 0
var resolvedField = field
if (schemaVersion > SUPPORTED_SCHEMA_VERSION) {
// If the document has a newer schema version, resolve via RemoteConfig.
val key = "v${SUPPORTED_SCHEMA_VERSION}_to_v${schemaVersion}"
val mapping = loadMapping(key)
val temp = mapping.get(field)
if (temp != null) {
resolvedField = temp.asString
}
}
Log.d(TAG, "Field resolved: $field --> $resolvedField")
return data[resolvedField]
}
/**
* Loads schema mapping instructions from RemoteConfig. Key string has the
* format: v{sourceVersion}_to_v{targetVersion}.
*/
private fun loadMapping(key: String): JsonObject {
if (!schemaMappings.containsKey(key)) {
val parser = JsonParser()
val mapping = remoteConfig.getString(key)
if (mapping.isNotEmpty()) {
schemaMappings[key] = parser.parse(mapping).asJsonObject
} else {
schemaMappings[key] = parser.parse("{}").asJsonObject
}
}
return schemaMappings[key]!!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment