#Cloudflare Worker with Hono + D1 + D1-ORM

5 messages · Page 1 of 1 (latest)

unreal ferry
#

Hello all, I am new to this thing and need some help. Currently, I've successfully setup worker with Hono + D1. Now I want to use D1-ORM (https://github.com/Interactions-as-a-Service/d1-orm) but don't know how to pass env.DB which is declared inside hono context like this:

app.get('/', async (c) => {
  const db = c.env.DB;
});

I've got ./src/Models/Customer.js file which contains this:

import { D1Orm, DataTypes, Model } from "d1-orm";

const orm = new D1Orm(env.DB);

const customer = new Model(
    {
        D1Orm: orm,
        tableName: "customers",
        primaryKeys: "id",
        autoIncrement: "id",
    },
    {
        CustomerId: {
            type: DataTypes.INTEGER,
            notNull: true,
        },
        CompanyName: {
            type: DataTypes.STRING,
            notNull: true,
        },
        ContactName: {
            type: DataTypes.STRING,
        },
    }
);

export default customer;

When I run wrangler dev I'm getting error:

service core:user:cf-api: Uncaught ReferenceError: env is not defined

Can anyone help me figure out how to properly pass env.DB to the model?
Thanks in advance. ❤️

wheat iron
#

I'd do something like

app.get('/', async (c) => {
  const db = c.env.DB;
  const orm = new D1Orm(env.DB);
  
  customer.SetOrm(orm);
});

And then don't include the orm in your initial definition of the model 🙂

unreal ferry
#

@wheat iron Thank you, that looks interesting and will try it out, but what if I want to have dozens of models, should I do the same for all?

wheat iron
#

Yes, that's the easiest way to get around it

#

The other way would be to make getting each model a function, that takes the orm and sets it - whichever you prefer