Skip to content

Wrapping the SQL Tag Function #1059

Open
@danhalliday

Description

@danhalliday

I have a load of simple queries to define, each returning one or many models which I have Typescript types for. At present I’m doing something like:

findById: async (id) => {
  const [user] = await sql<User[]>`
    SELECT *
    FROM users
    WHERE id = ${id}
  `
  return user ?? null
},

I would like to clean up the call sites to make the queries a bit more readable by creating a couple of helpers that do the whole thing inline — something like the following:

findById: async (id) => 
  await one`
    SELECT *
    FROM users
    WHERE id = ${id}
  `,

findMany: async (type) => 
  await many`
    SELECT *
    FROM users
    WHERE type = ${type}
  `,

But figuring out what types the wrapper tag functions need to have is a bit beyond me after looking through the Sql type’s definition.

All I really want to do is for many, pass through the result and cast it to the caller’s desired type, and for one, unwrap the first result and cast that to the caller’s desired type, which would be T | null.

Has anyone wrapped the sql tag function before and has the types handy, or knows how to do this?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions