Data Access

Once you have defined your data schema and routing, you'll want to be able to manage your data.

With SonicJs you can use the built in data access tier or interact directly with the 3 layers of data persistence:

  1. Cache (In-Memory)
  2. KV (Key-Value pair store)
  3. D1 (A SQLite SQL database)

It is recommend that you use the built in data-tier in order to get the benefits of caching, however this may not be suitable for all use-cases.


Here is a basic example below. This file is also located in the repo here:


import { Hono } from "hono";
import qs from "qs";
import { getData } from "../cms/data/data";

const example = new Hono();

example.get("/", (ctx) => {
  return c.text("Hello SonicJs!");

example.get("/users", async (ctx) => {
    var params = qs.parse(ctx.req.query());
    const data = await getData(ctx.env.D1DATA, ctx.env.KVDATA, 'users', params, ctx.req.url, 'fastest' );
    return ctx.json(data);

export { example };

Note: you will need to prefix your example route with v1 because of how its setup in src/server.ts, so to access your users example:


Let's take a closer look at a couple of the line above:

  var params = qs.parse(ctx.req.query());

This simply converts the urls parameters into an object using the qs plugin.

const data = await getData(ctx.env.D1DATA, ctx.env.KVDATA, 'users', params, ctx.req.url, 'fastest' );

Here, we're provided the D1DATA & KVDATA context object to the getData method so that it can determine which source it should use to lookup the data.

We pass in 'users' to indicate that we want to lookup data in the users table.

We're then passing in the params from the url that will typically contain limits, offsets, filters etc. See the table api for full details.

We also pass in the url. SonicJs uses the url as a key when setting the cache.

Lastly, we pass in fastest which indicates that we want the data to be pulled from whatever method is the fastest.