Created
November 30, 2019 09:33
-
-
Save toantran-ea/bde811a3fdbff089c05124fb26bac57d to your computer and use it in GitHub Desktop.
Data Repository
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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