Nicolas
Nicolas
Explore posts from servers
HHono
Created by Nicolas on 9/7/2024 in #help
Weird bug: JSON data not making it to server: RPC
No description
3 replies
SSolidJS
Created by Nicolas on 8/26/2024 in #support
Can't get fetch to work in server code
Hi all, I have a simple form and action like so:
import { action } from "@solidjs/router";
import { checkEligibility } from "~/lib/proxy/proxy";

const myAction = action(async (formData: FormData) => {
"use server";
const address = String(formData.get("address"))
const result = await checkEligibility(address);
console.log(result);
})

export default function Verify() {
return (
<form action={myAction} method="post">
<input
type="text"
name="address"
placeholder="Enter Address"
/>
<button
type="submit"
>
Verify
</button>
</form>
);
}
import { action } from "@solidjs/router";
import { checkEligibility } from "~/lib/proxy/proxy";

const myAction = action(async (formData: FormData) => {
"use server";
const address = String(formData.get("address"))
const result = await checkEligibility(address);
console.log(result);
})

export default function Verify() {
return (
<form action={myAction} method="post">
<input
type="text"
name="address"
placeholder="Enter Address"
/>
<button
type="submit"
>
Verify
</button>
</form>
);
}
And my function being called is like so:
export const checkEligibility = async (address: string) : Promise<z.infer<typeof checkResponse>> => {
console.log("Checking eligibility", address);
const brd_connectStr = "http://brd-customer-" + Resource.BrdUser.value + "-zone-" + Resource.BrdZone.value + ":" + Resource.BrdPassword.value + "@" + Resource.BrdSuperProxy.value;
console.log(brd_connectStr);
const baseUrl = "https://eligibility.sc.egov.usda.gov/eligibility/MapAddressVerification?";

console.log("About to fetch...");
const response = await fetch(baseUrl + new URLSearchParams({
address: address,
whichapp: "SHFPREV",
}).toString());

console.log(response);
// try to safely zod parse the response text
const result = await eligiblityResult.safeParseAsync(response.text)

console.log(result);

return {
isEligible: result.data?.eligibilityResult === "Eligible",
message: result.error?.message
}
}
export const checkEligibility = async (address: string) : Promise<z.infer<typeof checkResponse>> => {
console.log("Checking eligibility", address);
const brd_connectStr = "http://brd-customer-" + Resource.BrdUser.value + "-zone-" + Resource.BrdZone.value + ":" + Resource.BrdPassword.value + "@" + Resource.BrdSuperProxy.value;
console.log(brd_connectStr);
const baseUrl = "https://eligibility.sc.egov.usda.gov/eligibility/MapAddressVerification?";

console.log("About to fetch...");
const response = await fetch(baseUrl + new URLSearchParams({
address: address,
whichapp: "SHFPREV",
}).toString());

console.log(response);
// try to safely zod parse the response text
const result = await eligiblityResult.safeParseAsync(response.text)

console.log(result);

return {
isEligible: result.data?.eligibilityResult === "Eligible",
message: result.error?.message
}
}
But for some reason when i try to submit the form and run this code, it only gets to right before the fetch since it console logs About to fetch... but it never logs the response. There is no error being thrown, or anything at all. I checked the browser console and my server logs (showing About to fetch...), but nothing shows after that. What could be going wrong?
6 replies
DTDrizzle Team
Created by Nicolas on 8/11/2024 in #help
SQL string could not be parsed: non-terminated block comment at ...
Hi all, I am using Turso and I added two properties to my users table created_at and updated_at. I successfully generated a migration file, which looks like this:
ALTER TABLE `users` ADD `created_at` text DEFAULT (current_timestamp) NOT NULL;--> statement-breakpoint
ALTER TABLE `users` ADD `updated_at` text DEFAULT (current_timestamp) NOT NULL;
ALTER TABLE `users` ADD `created_at` text DEFAULT (current_timestamp) NOT NULL;--> statement-breakpoint
ALTER TABLE `users` ADD `updated_at` text DEFAULT (current_timestamp) NOT NULL;
This is my schema:
import { sql } from 'drizzle-orm';
import { boolean } from 'drizzle-orm/mysql-core';
import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
import { createInsertSchema, createSelectSchema } from 'drizzle-zod';

export const users = sqliteTable('users', {
id: text('id').primaryKey(),
name: text('name').notNull(),
email: text('email').unique().notNull(),
subscribed: integer('subscribed', { mode: "boolean"}).notNull(), // Store subscription type
google_id: text('google_id').unique().notNull(), // Store Google ID for authentication
created_at: text('created_at').notNull().default(sql`(current_timestamp)`), <--- NEW
updated_at: text('updated_at').notNull().default(sql`(current_timestamp)`), <--- NEW
});

export const sessions = sqliteTable('sessions', {
id: text('id').primaryKey(),
expires_at: integer('expires_at').notNull(),
user_id: text('user_id').notNull().references(() => users.id),
});

export type InsertUser = typeof users.$inferInsert;
export const zInsertUser = createInsertSchema(users);
export type SelectUser = typeof users.$inferSelect;
import { sql } from 'drizzle-orm';
import { boolean } from 'drizzle-orm/mysql-core';
import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
import { createInsertSchema, createSelectSchema } from 'drizzle-zod';

export const users = sqliteTable('users', {
id: text('id').primaryKey(),
name: text('name').notNull(),
email: text('email').unique().notNull(),
subscribed: integer('subscribed', { mode: "boolean"}).notNull(), // Store subscription type
google_id: text('google_id').unique().notNull(), // Store Google ID for authentication
created_at: text('created_at').notNull().default(sql`(current_timestamp)`), <--- NEW
updated_at: text('updated_at').notNull().default(sql`(current_timestamp)`), <--- NEW
});

export const sessions = sqliteTable('sessions', {
id: text('id').primaryKey(),
expires_at: integer('expires_at').notNull(),
user_id: text('user_id').notNull().references(() => users.id),
});

export type InsertUser = typeof users.$inferInsert;
export const zInsertUser = createInsertSchema(users);
export type SelectUser = typeof users.$inferSelect;
When running the migration, i get the following error:
[⣯] applying migrations...LibsqlError: SQL_PARSE_ERROR: SQL string could not be parsed: non-terminated block comment at (3, 1)
at mapHranaError (file:///home/ubuntu/reap-checker/node_modules/@libsql/client/lib-esm/hrana.js:257:16)
at HttpClient.batch (file:///home/ubuntu/reap-checker/node_modules/@libsql/client/lib-esm/http.js:82:19)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at LibSQLSession.batch (/home/ubuntu/reap-checker/node_modules/src/libsql/session.ts:75:24)
at migrate (/home/ubuntu/reap-checker/node_modules/src/libsql/migrator.ts:50:2) {
code: 'SQL_PARSE_ERROR',
rawCode: undefined,
[cause]: [ResponseError: SQL string could not be parsed: non-terminated block comment at (3, 1)] {
code: 'SQL_PARSE_ERROR',
proto: {
message: 'SQL string could not be parsed: non-terminated block comment at (3, 1)',
code: 'SQL_PARSE_ERROR'
}
}
}
[⣯] applying migrations...LibsqlError: SQL_PARSE_ERROR: SQL string could not be parsed: non-terminated block comment at (3, 1)
at mapHranaError (file:///home/ubuntu/reap-checker/node_modules/@libsql/client/lib-esm/hrana.js:257:16)
at HttpClient.batch (file:///home/ubuntu/reap-checker/node_modules/@libsql/client/lib-esm/http.js:82:19)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at LibSQLSession.batch (/home/ubuntu/reap-checker/node_modules/src/libsql/session.ts:75:24)
at migrate (/home/ubuntu/reap-checker/node_modules/src/libsql/migrator.ts:50:2) {
code: 'SQL_PARSE_ERROR',
rawCode: undefined,
[cause]: [ResponseError: SQL string could not be parsed: non-terminated block comment at (3, 1)] {
code: 'SQL_PARSE_ERROR',
proto: {
message: 'SQL string could not be parsed: non-terminated block comment at (3, 1)',
code: 'SQL_PARSE_ERROR'
}
}
}
Any idea what's going on? This is a super simple migration, just adding 2 columns, so not sure what to do... Thanks
6 replies
CDCloudflare Developers
Created by Nicolas on 3/16/2024 in #pages-help
How to Interact with Service Workers from Pages Functions
No description
2 replies
TtRPC
Created by Nicolas on 2/16/2024 in #❓-help
No "mutation"-procedure on path
Hello all, I am using the latest version of TRPC on my client and server. I am using React Query on my client and AWS Lambda on my server side. When trying to perform a test mutation:
export default function () {
const organizationCreate = trpc.insert_superUser.useMutation();
const insertTestOrg = async () => {
const repsonse = organizationCreate.mutate({
name: "Test Organization",
description: "Test Description",
}, {
onError: (error) => {
console.log("Error", error);
}
})
}
return (<div>
<Button variant="primary" onClick={() => insertTestOrg()}>Button</Button>
</div>)
}
export default function () {
const organizationCreate = trpc.insert_superUser.useMutation();
const insertTestOrg = async () => {
const repsonse = organizationCreate.mutate({
name: "Test Organization",
description: "Test Description",
}, {
onError: (error) => {
console.log("Error", error);
}
})
}
return (<div>
<Button variant="primary" onClick={() => insertTestOrg()}>Button</Button>
</div>)
}
I get the following error Error TRPCClientError: No "mutation"-procedure on path "insert_superUser" I am using a Meta to make sure only users of a specified role can call certain functions, like so:
interface Meta {
role: Role;
}
const t = initTRPC.context<Context>().meta<Meta>().create({
defaultMeta: {
role: Role.OrganizationUser
}
});

export const authRoleProcedure = t.procedure.use(async (opts) => {
const { meta, next, ctx } = opts;
if (!meta?.role) {
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'Role not defined in meta' });
}
if (!ctx.user) {
throw new TRPCError({ code: 'BAD_REQUEST', message: 'User not defined in context'});
}
if (ctx.user.role > meta.role) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: `User does not have the required role. Required: ${meta.role}, User: ${ctx.user.role}`});
}
console.log('User has the required role')
return next();
});

export const router = t.router;
interface Meta {
role: Role;
}
const t = initTRPC.context<Context>().meta<Meta>().create({
defaultMeta: {
role: Role.OrganizationUser
}
});

export const authRoleProcedure = t.procedure.use(async (opts) => {
const { meta, next, ctx } = opts;
if (!meta?.role) {
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'Role not defined in meta' });
}
if (!ctx.user) {
throw new TRPCError({ code: 'BAD_REQUEST', message: 'User not defined in context'});
}
if (ctx.user.role > meta.role) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: `User does not have the required role. Required: ${meta.role}, User: ${ctx.user.role}`});
}
console.log('User has the required role')
return next();
});

export const router = t.router;
3 replies
DTDrizzle Team
Created by Nicolas on 2/14/2024 in #help
Getting error NeonDbError when pushing migration file
Hi all, So i have a schema that defines custom type JSON objects for my NeonDB database, like so:
type Address = {
street: string;
city: string;
state: string;
zip: string;
};
type Address = {
street: string;
city: string;
state: string;
zip: string;
};
And I am trying to use it like so:
export const Organizations = vendorPortalSchema.table('organizations', {
id: serial("id").primaryKey(),
name: text("name").unique().notNull(),
description: text("description"),
location: json("location").$type<Address>(),
logo_picture_file_id: serial("logo_picture_file_id").references(
(): AnyPgColumn => Files.id
),
});
export const Organizations = vendorPortalSchema.table('organizations', {
id: serial("id").primaryKey(),
name: text("name").unique().notNull(),
description: text("description"),
location: json("location").$type<Address>(),
logo_picture_file_id: serial("logo_picture_file_id").references(
(): AnyPgColumn => Files.id
),
});
However, I am getting an error NeonDbError: data type json has no default operator class for access method "btree" So perhaps I am not specifying the custom type of json correctly, but I could not find any examples on the drizzle website. I also tried like (commads instead of semi-colons):
type Address = {
street: string,
city: string,
state: string,
zip: string,
};
type Address = {
street: string,
city: string,
state: string,
zip: string,
};
But it still lead to the same error. Any thoughts on how to do this properly? Thank you!
4 replies
RRefine
Created by harsh-harlequin on 2/4/2024 in #ask-any-question
Error Creating New Refine App
Hello all, I am running into errors trying to start a new refine app. Here is what I did: npm create refine-app@latest
✔ Downloaded remote source successfully.
✔ Choose a project template · refine-vite
✔ What would you like to name your project?: · frontend
✔ Choose your backend service to connect: · data-provider-custom-json-rest
✔ Do you want to use a UI Framework?: · chakra
✔ Do you want to add example pages?: · inferencer
✔ Do you need any Authentication logic?: · auth-provider-google
✔ Do you need i18n (Internationalization) support?: · no
✔ Choose a package manager: · npm
✔ Downloaded remote source successfully.
✔ Choose a project template · refine-vite
✔ What would you like to name your project?: · frontend
✔ Choose your backend service to connect: · data-provider-custom-json-rest
✔ Do you want to use a UI Framework?: · chakra
✔ Do you want to add example pages?: · inferencer
✔ Do you need any Authentication logic?: · auth-provider-google
✔ Do you need i18n (Internationalization) support?: · no
✔ Choose a package manager: · npm
When running npm run dev I get this error:
✘ [ERROR] Could not resolve "graphql"

node_modules/graphql-tag/lib/index.js:2:22:
2 │ import { parse } from 'graphql';
╵ ~~~~~~~~~

You can mark the path "graphql" as external to exclude it from the bundle, which will remove this error.
✘ [ERROR] Could not resolve "graphql"

node_modules/graphql-tag/lib/index.js:2:22:
2 │ import { parse } from 'graphql';
╵ ~~~~~~~~~

You can mark the path "graphql" as external to exclude it from the bundle, which will remove this error.
I am not sure what depends on graphql, so i don't want to remove it. Seeing as this is just a simple refine app created from the official CLI, I am assuming this should work out of the box, but I may be wrong based on my configuration. Thanks!
5 replies
WWindmill
Created by Nicolas on 2/3/2024 in #help
How to Incorporate MinIO with Windmill Docker Compose
Hi all, I am new to Windmill and docker in general, and I am trying to incorporate MiniO so I can do file uploads for images and other files, however, I cannot get this to work with the docker-compose provided by Windmill and the official docker-compose provided by MiniO here: https://hub.docker.com/r/bitnami/minio Attached is my docker-compose. I am getting the error:
windmill_server-1 | Error: Connecting to database: error communicating with database: failed to lookup address information: Name or service not known
windmill_server-1 | Error: Connecting to database: error communicating with database: failed to lookup address information: Name or service not known
All other containers are launching just fine, but the windmill-windmill_server_1 errors out with the above error and keeps restarting. Am I not assigning the proper linkage to MiniO to the correct service in the docker-compose? Any guidance on this would be great, not sure if I am thinking of this properly. Thank you!
6 replies
TtRPC
Created by Nicolas on 11/17/2023 in #❓-help
Creating inner context for AWS Lambda Context Options
Hi All, I have been using tRPC for many routes, and I have started to realize I need to call certain routes on the server-side (lambda / serverless in my case), and so I was trying to follow the documentation on how to create an inner context / outer context so I can call my tRPC routes from other routes, but I am stuck and I am confused on how to go about doing it for AWS lambda context as the documentation example is rather simple. This is what I have so far:
import { inferAsyncReturnType } from "@trpc/server";
import type { CreateAWSLambdaContextOptions } from "@trpc/server/adapters/aws-lambda";
import type { APIGatewayProxyEventV2 } from "aws-lambda";
import { CognitoJwtVerifier } from "aws-jwt-verify";

/**
* Defines your inner context shape.
* Add fields here that the inner context brings.
*/
interface CreateInnerContextOptions extends Partial<CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>>{
context: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>["context"] | undefined;
event: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>["event"] | undefined;

}

/**
* Inner context. Will always be available in your procedures, in contrast to the outer context.
*
* Also useful for:
* - testing, so you don't have to mock Next.js' `req`/`res`
* - tRPC's `createServerSideHelpers` where we don't have `req`/`res`
*
* @see https://trpc.io/docs/context#inner-and-outer-context
*/
export async function createContextInner(opts?: CreateInnerContextOptions) {
return {
context: opts?.context,
event: opts?.event,
};
}

/**
* Outer context. Used in the routers and will e.g. bring `req` & `res` to the context as "not `undefined`".
*
* @see https://trpc.io/docs/context#inner-and-outer-context
*/

export async function createContext({ event }: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) {
async function getUserFromHeader() {
// Verifier that expects valid access tokens:
if (process.env.USER_POOL_ID === undefined || process.env.USER_POOL_CLIENT_ID == undefined) {
throw new Error("Missing environment variables");
}
if (event.headers.authorization) {
const token = event.headers.authorization.split(" ")[1];
const verifier = CognitoJwtVerifier.create({
userPoolId: process.env.USER_POOL_ID,
tokenUse: "id",
clientId: process.env.USER_POOL_CLIENT_ID,
});
// the Authorization header will contain the JWT token as a Bearer token, we need to remove the Bearer part before we can verify the token
const payload = await verifier.verify(token);
return {
role: payload["cognito:groups"],
username: payload["cognito:username"],
orgId: payload["custom:organizationId"] ? (payload["custom:organizationId"] as string) : undefined,
};
}
throw new Error("No authorization header");
}
const user = await getUserFromHeader();

const contextInner = await createContextInner({ context: undefined, event: undefined });

return {
...contextInner,
event: event,
apiVersion: (event as { version?: string }).version ?? "1.0",
user: user,
};
}



export type Context = inferAsyncReturnType<typeof createContextInner>;
import { inferAsyncReturnType } from "@trpc/server";
import type { CreateAWSLambdaContextOptions } from "@trpc/server/adapters/aws-lambda";
import type { APIGatewayProxyEventV2 } from "aws-lambda";
import { CognitoJwtVerifier } from "aws-jwt-verify";

/**
* Defines your inner context shape.
* Add fields here that the inner context brings.
*/
interface CreateInnerContextOptions extends Partial<CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>>{
context: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>["context"] | undefined;
event: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>["event"] | undefined;

}

/**
* Inner context. Will always be available in your procedures, in contrast to the outer context.
*
* Also useful for:
* - testing, so you don't have to mock Next.js' `req`/`res`
* - tRPC's `createServerSideHelpers` where we don't have `req`/`res`
*
* @see https://trpc.io/docs/context#inner-and-outer-context
*/
export async function createContextInner(opts?: CreateInnerContextOptions) {
return {
context: opts?.context,
event: opts?.event,
};
}

/**
* Outer context. Used in the routers and will e.g. bring `req` & `res` to the context as "not `undefined`".
*
* @see https://trpc.io/docs/context#inner-and-outer-context
*/

export async function createContext({ event }: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) {
async function getUserFromHeader() {
// Verifier that expects valid access tokens:
if (process.env.USER_POOL_ID === undefined || process.env.USER_POOL_CLIENT_ID == undefined) {
throw new Error("Missing environment variables");
}
if (event.headers.authorization) {
const token = event.headers.authorization.split(" ")[1];
const verifier = CognitoJwtVerifier.create({
userPoolId: process.env.USER_POOL_ID,
tokenUse: "id",
clientId: process.env.USER_POOL_CLIENT_ID,
});
// the Authorization header will contain the JWT token as a Bearer token, we need to remove the Bearer part before we can verify the token
const payload = await verifier.verify(token);
return {
role: payload["cognito:groups"],
username: payload["cognito:username"],
orgId: payload["custom:organizationId"] ? (payload["custom:organizationId"] as string) : undefined,
};
}
throw new Error("No authorization header");
}
const user = await getUserFromHeader();

const contextInner = await createContextInner({ context: undefined, event: undefined });

return {
...contextInner,
event: event,
apiVersion: (event as { version?: string }).version ?? "1.0",
user: user,
};
}



export type Context = inferAsyncReturnType<typeof createContextInner>;
5 replies
DTDrizzle Team
Created by Nicolas on 10/11/2023 in #help
Infer Types from Partial Select Prepared Statement
No description
5 replies
DTDrizzle Team
Created by Nicolas on 10/9/2023 in #help
Null fields not working as expected
Hi all, I am using Drizzle ORM with Zod validation for useForm, and I am running into issues with fields that are allowed to be undefined / null, but I get Zod errors stating that the value of the optional fields (when left empty) are invalid_type and in required. I was able to fix this by refining the field as follows:
export const selectDeploymentSchema = createSelectSchema(deployments, {
city: (deployments) => deployments.city.nullish(),
});
export const selectDeploymentSchema = createSelectSchema(deployments, {
city: (deployments) => deployments.city.nullish(),
});
This allows the city field to be left blank, but by default, even though i didn't specify notNull() on that field, Zod would error out saying that the field is required. I am using Turso DB, so this is my schema:
export const deployments = sqliteTable("deployments", {
id: integer("id").primaryKey(),
organizationId: integer("organization_id")
.notNull()
.references(() => organizations.id),
name: text("name").notNull().unique(),
description: text("description"),
streetAddress: text("street_address"),
city: text("city"),
state: text("state"),
zip: text("zip"),
});
export const deployments = sqliteTable("deployments", {
id: integer("id").primaryKey(),
organizationId: integer("organization_id")
.notNull()
.references(() => organizations.id),
name: text("name").notNull().unique(),
description: text("description"),
streetAddress: text("street_address"),
city: text("city"),
state: text("state"),
zip: text("zip"),
});
Notice for all fields by the id, organizationId, and name, they are optional; however, Zod treats them as ZodNullable but they should in fact be treated as ZodOptional<ZodNullable<ZodString>> to allow my fields to be empty (as is the intended affect).
2 replies
TtRPC
Created by Nicolas on 9/30/2023 in #❓-help
Basic Inference not Working
I have been struggling to get basic type inferencing to work with trpc, react, and Drizzle ORM. This is what my server-side router is returning from the list method:
export const organizationRouter = router({
list: adminProcedure.query(async () => {
const response = await listOrganizations.all();
return response;
}),
export const organizationRouter = router({
list: adminProcedure.query(async () => {
const response = await listOrganizations.all();
return response;
}),
Where, if I hover over the response in the return, it says the type is:
const response: {
id: number;
name: string;
description: string | null;
}[]
const response: {
id: number;
name: string;
description: string | null;
}[]
However, on my client side, it says the type is any for the following:
const organizationData = trpc.organization.list.useQuery();
organizationData.data <---- ANY
const organizationData = trpc.organization.list.useQuery();
organizationData.data <---- ANY
Why is this basic type inferencing not happening? I am using Drizzle ORM to infer the return type on the router response; could this have something to do with it? Does trpc not work well with ORM's that use inference?
3 replies
DTDrizzle Team
Created by Nicolas on 9/30/2023 in #help
notNull() is still letting field be optional
I am performing the following for SQLite:
export const products = sqliteTable("products", {
id: integer("id").primaryKey({ autoIncrement: false }).notNull(),
name: text("name").notNull(),
description: text("description"),
});
export const products = sqliteTable("products", {
id: integer("id").primaryKey({ autoIncrement: false }).notNull(),
name: text("name").notNull(),
description: text("description"),
});
However, when I perform: export type NewProduct = typeof products.$inferInsert; It says that id is optional (this is what it shows when i hover over NewProduct)
type NewProduct = {
name: string;
id?: number | undefined; <---- SHOULD JUST BE NUMBER
description?: string | null | undefined;
}
type NewProduct = {
name: string;
id?: number | undefined; <---- SHOULD JUST BE NUMBER
description?: string | null | undefined;
}
How can I fix this?
8 replies
DTDrizzle Team
Created by Nicolas on 9/30/2023 in #help
Explanation on execute() vs all() vs get() vs run()
I am using prepare() to make prepared statements for Turso (so SQLite), and the docs use prepare.all() for SQLite instead of prepare.execute() as is used for PostgreSQL and MySQL, why is that? Same goes for prepare.get() for SQLite instead of prepare.execute() When do I know when to run those different queries for SQLite? Thank you!
1 replies
DTDrizzle Team
Created by Nicolas on 9/29/2023 in #help
Issue Pushing Schema to Turso
Hi All, I made a schema.ts with sqliteTable statements, and I created a drizzle.config.ts as follows:
import { Config } from "drizzle-kit";

export default {
driver: "turso",
dbCredentials: {
url: "libsql://[TABLE]-[GITHUB].turso.io",
authToken:
"[TOKEN]",
},
schema: "./schema.ts",
out: "./out",
} as Config;
import { Config } from "drizzle-kit";

export default {
driver: "turso",
dbCredentials: {
url: "libsql://[TABLE]-[GITHUB].turso.io",
authToken:
"[TOKEN]",
},
schema: "./schema.ts",
out: "./out",
} as Config;
And when I try running pnpm drizzle-kit push:sqlite, I get the following error regarding that it cannot find module better-sqlite3:
drizzle-kit: v0.19.13
drizzle-orm: v0.28.6

node:internal/modules/cjs/loader:1048
const err = new Error(message);
^

Error: Cannot find module 'better-sqlite3'
Require stack:
- /workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs
at Module._resolveFilename (node:internal/modules/cjs/loader:1048:15)
at Module._load (node:internal/modules/cjs/loader:901:27)
at Module.require (node:internal/modules/cjs/loader:1115:19)
at require (node:internal/modules/helpers:130:18)
at node_modules/.pnpm/@libsql+client@0.1.6/node_modules/@libsql/client/lib-esm/sqlite3.js (/workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs:43596:37)
at __init (/workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs:9:56)
at node_modules/.pnpm/@libsql+client@0.1.6/node_modules/@libsql/client/lib-esm/index.js (/workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs:51852:5)
at __init (/workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs:9:56)
at src/cli/commands/sqliteIntrospect.ts (/workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs:51875:5)
at __init (/workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs:9:56) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs'
]
}
drizzle-kit: v0.19.13
drizzle-orm: v0.28.6

node:internal/modules/cjs/loader:1048
const err = new Error(message);
^

Error: Cannot find module 'better-sqlite3'
Require stack:
- /workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs
at Module._resolveFilename (node:internal/modules/cjs/loader:1048:15)
at Module._load (node:internal/modules/cjs/loader:901:27)
at Module.require (node:internal/modules/cjs/loader:1115:19)
at require (node:internal/modules/helpers:130:18)
at node_modules/.pnpm/@libsql+client@0.1.6/node_modules/@libsql/client/lib-esm/sqlite3.js (/workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs:43596:37)
at __init (/workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs:9:56)
at node_modules/.pnpm/@libsql+client@0.1.6/node_modules/@libsql/client/lib-esm/index.js (/workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs:51852:5)
at __init (/workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs:9:56)
at src/cli/commands/sqliteIntrospect.ts (/workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs:51875:5)
at __init (/workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs:9:56) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/workspaces/reserve-power/node_modules/.pnpm/drizzle-kit@0.19.13/node_modules/drizzle-kit/index.cjs'
]
}
Am I not pushing the schema properly with the command drizzle-kit push:sqlite? Thank you!
3 replies
DTDrizzle Team
Created by Nicolas on 9/27/2023 in #help
How to make sql.placeholder() type safe
I have the following prepared statement:
export const listDeployments = db
.select()
.from(deployments)
.where(eq(deployments.organizationId, sql.placeholder("orgId")))
.prepare("listDeployments");
export const listDeployments = db
.select()
.from(deployments)
.where(eq(deployments.organizationId, sql.placeholder("orgId")))
.prepare("listDeployments");
However, when I use this like below: const response = await listDeployments.execute({ orgId: input }); The orgId is not type safe, I can enter whatever string I want, and there is no way to protect this call from receiving something other than orgId Is there a way to make it such that the caller must pass in orgId? Thank you!
4 replies
DTDrizzle Team
Created by Nicolas on 9/23/2023 in #help
Neon and Drizzle ORM: Can my schema.ts create my tables in Neon?
As the title suggests, I was wondering if Drizzle ORM can create my tables in Neon from my schema.ts, or if I need to first create my tables in Neon with SQL, and then just create my schema.ts to reflect those tables. Thank you!
7 replies
TtRPC
Created by Nicolas on 8/31/2023 in #❓-help
Issue Inferring Type on Frontend with ElectroDB Query Return Statement
No description
3 replies
RRefine
Created by quickest-silver on 8/28/2023 in #ask-any-question
Add Type to useForm
How do I make the object that I am manipulating, with the help of useForm hook, type safe? For instance, I know I can do things like:
<TextField
{...register("email", {
required: "This field is required",
pattern: {
value: /\S+@\S+\.\S+/,
message: "Please enter a valid email address",
},
})}
error={!!(errors as any)?.email}
helperText={(errors as any)?.email?.message}
margin="normal"
fullWidth
InputLabelProps={{ shrink: true }}
type="email"
label={"Email"}
name="email"
/>
<TextField
{...register("email", {
required: "This field is required",
pattern: {
value: /\S+@\S+\.\S+/,
message: "Please enter a valid email address",
},
})}
error={!!(errors as any)?.email}
helperText={(errors as any)?.email?.message}
margin="normal"
fullWidth
InputLabelProps={{ shrink: true }}
type="email"
label={"Email"}
name="email"
/>
But how do i ensure email is type-safe with respect to some interface? For instance, I have a user interface that I would like to apply to my useForm, so that way I make sure I only perform the proper useForm actions on the fields that exist for user
5 replies
RRefine
Created by xenial-black on 8/22/2023 in #ask-any-question
MUI Inferencer Can't Detect Object Inside Entity
No description
5 replies