Database
Docs: https://docs.api.kunkun.sh/interfaces/index.IDb
Database API is for extensions that need to store data in a database.
Please avoid using browser storage like localStorage to avoid data collisions with other extensions and data leaks.
Database API doesn’t require any permissions, but one extension can only access its own data.
This database is based on sqlite, for a key-value style storage, see KV API.
The following APIs are now available:
adddeletesearchretrieveAllretrieveAllByTypedeleteAllupdate
CRUD are the basic operations provided by the database API. Let’s talk about them one by one.
Add
There are 3 parameters for each data entry:
data- Any data you want to store.
dataType- An arbitrary string to categorize the data.
searchText- A string to search the data. You can use this to store preview data as well.
- This field is searchable via sqlite full-text search.
Only data is required. dataType and searchText are optional, and everything is stored as a string.
You need to use JSON.stringify to store objects, and JSON.parse to deserialize them.
Later I may provide a way to store objects directly, but for now, you need to serialize them.
import { db } from "@kksh/api/ui/template";import { db } from "@kksh/api/ui/custom";import { db } from "@kksh/api/headless";await db.add({ data: JSON.stringify({ name: "Kunkun" }), dataType: "preference", searchText: "preference",});Read/Search
There are multiple APIs to read data from the database.
db.retrieveAllreturns all data entries for the extension. Sometimes the extension may store large amount of data in thedatafield, while you may only need thesearchText. So afieldsparameter is provided to specify which fields you want to retrieve.db.retrieveAllByTypereturns all data entries bydataType.db.searchrun search query within the database instead of retrieving all data and filtering them with JS.
const allData = await db.retrieveAll({ fields: ["data", "search_text"],});
const result = await db.search({ dataType: "preference" });
const result = await db.search({ dataType: "preference" });Search
db.search API supports searching on multiple fields. Use your IDE to go to the definition of search() to see the full type definition.
enum SQLSortOrder { ASC = "ASC", DESC = "DESC",}
type SearchParams = { dataId?: number; fullTextSearch?: boolean; dataType?: string; searchText?: string; afterCreatedAt?: Date; beforeCreatedAt?: Date; limit?: number; orderByCreatedAt?: SQLSortOrder; orderByUpdatedAt?: SQLSortOrder; fields?: ExtDataField[];};dataIdis the unique ID of the data entry.fullTextSearchis a boolean to enable full-text search on thesearchTextfield.limitis the maximum number of results to return.fieldsis an array of fields to return.
Update
You need to provide the dataId to update the data.
await db.update({ dataId: 803, data: "new data", searchText: "new data" });Delete
You need to provide the dataId to delete the data.
await db.delete(803);