Read the original article:Key Standardization for Preferences
Context
If we want to use a string value as a key in the preferences database, what approach should we follow?
Description
Preferences technology works as a key-value database. In this context, the 'key' is generally assigned as an ID. However, in certain cases—such as when dealing with a list of elements that do not have an assigned ID—string values like names might be used as keys. In such situations, these values should go through a standardization process to ensure consistency and reliability.
Solution / Approach
For example, let's assume we are developing a wearable HarmonyOS application where we want to store the duration of exercises performed by the user using the local preferences database. In this case, since we know that exercise names are unique, we can use these names as keys. By applying a specific standardization rule, we can generate consistent keys from the exercise names as shown below.
import preferences from '@ohos.data.preferences';
const PREF_NAME = 'exercise_achievements';
let exercisePrefs: preferences.Preferences;
export function createSafeKey(exerciseName: string): string {
return exerciseName
.trim()
.toLowerCase()
.replace(/\s+/g, '_')
.replace(/[^a-z0-9_]/g, '');
}
export async function initExercisePrefs(context: Context) {
exercisePrefs = preferences.getPreferencesSync(context, { name: PREF_NAME });
}
export async function saveExerciseDuration(exerciseName: string, seconds: number) {
console.log('saved: '+seconds)
const key = createSafeKey(exerciseName) + '_total_seconds';
const current = Number(await exercisePrefs.get(key, 0));
if (isNaN(current)) {
console.error('Invalid stored value, resetting to 0');
await exercisePrefs.put(key, seconds);
} else {
await exercisePrefs.put(key, current + seconds);
}
await exercisePrefs.flush();
}
export async function getTotalDuration(exerciseName: string): Promise<number> {
return Number(await exercisePrefs.get(`${createSafeKey(exerciseName)}_total_seconds`, 0)) || 0;
}
As seen in the example above, the createSafeKey method is designed to generate a safe and consistent key based on a given string. The key point here is that this method is not only used when saving data to the database, but also when retrieving data from it. For instance, in the getTotalDuration method, a key generated using createSafeKey is used to fetch the corresponding value from the database.
Key Takeaways
- In the given example, the parameter used to generate the key is of type
String. Accordingly, methods liketrim(),toLowerCase(), andreplace()are applied, which are specific to string-type parameters. On the other hand, values of typenumbercan be used directly without any transformation. - The method or code block responsible for the transformation can be used in the same way across different modules in a modular application.
Additional Resources
https://developer.huawei.com/consumer/en/doc/harmonyos-guides/data-persistence-by-preferences
Top comments (0)