Skip to content

Instantly share code, notes, and snippets.

@toantran-ea
Created November 30, 2019 09:33
Show Gist options
  • Save toantran-ea/bde811a3fdbff089c05124fb26bac57d to your computer and use it in GitHub Desktop.
Save toantran-ea/bde811a3fdbff089c05124fb26bac57d to your computer and use it in GitHub Desktop.
Data Repository
package com.example.demo.data
import com.google.appengine.api.datastore.*
class DataRepository {
private val dataStore = DatastoreServiceFactory.getDatastoreService()
private val foodIntakeEntry = dataStore.prepare(Query(FOOD_INTAKE_ENTRY))
// READ
fun listAll(): List<FoodEntry> =
foodIntakeEntry.asList(FetchOptions.Builder.withDefaults()).map { it.toEntry() }
// CREATE/UPDATE
fun save(entries: List<FoodEntry>): List<Key> {
entries.map { it.toEntity() }.also { return dataStore.put(it) }
}
private fun FoodEntry.toEntity() = Entity(FOOD_INTAKE_ENTRY, id).apply {
setProperty("id", id)
setProperty("name", name)
setProperty("time", time)
setProperty("description", description)
setProperty("energyCount", energyCount)
setProperty("updated", updated)
}
private fun Entity.toEntry() = FoodEntry(
id = getProperty("id") as Long,
name = getProperty("name") as String,
description = getProperty("description") as String,
time = getProperty("time") as Long,
energyCount = getProperty("energyCount") as Long,
updated = getProperty("updated") as Long
)
companion object {
const val FOOD_INTAKE_ENTRY = "FoodIntakeEntry"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment