next.js Drizzle ORM中的模块化SELECT语句

efzxgjgh  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(128)

我有一个使用Drizzle ORM查询数据库的函数,并接受各种选项,如enabledlimit,以及未来可能更多的选项。我正在寻找一种更简洁和模块化的方式来处理我的函数中的这些选项。
下面是当前的实现:

type Options = {
    enabled?: boolean,
    limit?: number,
    // Potentially more options in the future
}

async function getAddresses(contactId: number, options: Options): Promise<InferSelectModel<typeof addressSchema>[]> {
    if (options.enabled !== undefined && options.limit) {
        return db.select().from(addressSchema).where(and(eq(addressSchema.contactId, contactId), eq(addressSchema.enabled, options.enabled))).limit(options.limit)
    } else if (options.enabled !== undefined && options.limit === 0) {
        return db.select().from(addressSchema).where(and(eq(addressSchema.contactId, contactId), eq(addressSchema.enabled, options.enabled)))
    } else if (options.limit) {
        return db.select().from(addressSchema).where(eq(addressSchema.contactId, contactId)).limit(options.limit)
    } else {
        return db.select().from(addressSchema).where(and(eq(addressSchema.contactId, contactId))
    }
}

字符串
我想在使用Drizzle ORM时简化这段代码,使其更加模块化,并为未来可能的选项(例如,偏移选项)做好准备。如何使用Drizzle ORM实现更优雅和更易于维护的解决方案?

o2gm4chl

o2gm4chl1#

您可以使用动态查询构建,如drizzle文档中所示:https://orm.drizzle.team/docs/dynamic-query-building
为每个要有条件应用的参数定义一个函数,例如:

function withLimit<T extends PgSelect>(qb: T, limit) {
  if (limit !== undefined) {
    return qb.limit(limit)
  }
  return qb
}

字符串
然后,您可以通过应用每个函数来构建查询,例如:

let qb = db.select().from(addressSchema).$dynamic()
qb = withLimit(qb, options.limit)
// use await qb or qb.then to get your result

相关问题