KWAC
KWAC
Explore posts from servers
CDCloudflare Developers
Created by KWAC on 7/31/2024 in #d1-database
I'm using nuxt + drizzle orm +
I am running my Nuxt application locally, but it is configured to connect to a remote Cloudflare D1 database
2 replies
DTDrizzle Team
Created by KWAC on 7/31/2024 in #help
quering with nuxt + drizzle + cloudflare D1
Here's a snippet from my signup.vue page making api call:
const signupData = {
firstname: this.firstnameSignUp,
lastname: this.lastnameSignUp,
email: this.emailSignUp,
username: this.usernameSignUp,
password: this.passwordSignUp,
confirm_password: this.confirm_password,
country: this.selectedCountry,
gender: this.gender,
phone: this.phone,
selectedPhoneCode: this.selectedPhoneCode,
date_of_birth: this.date_of_birth,
terms: this.terms
};

const response = await fetch('/api/login/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(signupData)
});

const result = await response.json();

if (!result.success) {
this.errors = result.errors;
} else {
await navigateTo('/verify');
}
const signupData = {
firstname: this.firstnameSignUp,
lastname: this.lastnameSignUp,
email: this.emailSignUp,
username: this.usernameSignUp,
password: this.passwordSignUp,
confirm_password: this.confirm_password,
country: this.selectedCountry,
gender: this.gender,
phone: this.phone,
selectedPhoneCode: this.selectedPhoneCode,
date_of_birth: this.date_of_birth,
terms: this.terms
};

const response = await fetch('/api/login/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(signupData)
});

const result = await response.json();

if (!result.success) {
this.errors = result.errors;
} else {
await navigateTo('/verify');
}
Data is not inserted into a table from api call. But from drizzle kit studio (using D1) I can modify data without problems. Am I doing something wrong here?
3 replies
DTDrizzle Team
Created by KWAC on 7/31/2024 in #help
quering with nuxt + drizzle + cloudflare D1
my api (api/login/signup.post.js) looks like this:
import { generateId } from "lucia";
import { user } from "@/server/db/schema.ts";

export default defineEventHandler(async (event) => {

const lucia = event.context.lucia;
const db = event.context.db;

const body = await readBody(event);

const {
firstname,
lastname,
email,
username,
password,
confirm_password,
country,
gender,
phone,
selectedPhoneCode,
date_of_birth,
terms
} = body;


try{
await db.insert(user).values({
id: userId,
firstname: firstname,
lastname: lastname,
email: email,
username: username,
password: password,
confirm_password: confirm_password,
country: country,
gender: gender,
date_of_birth: date_of_birth,
selectedPhoneCode: selectedPhoneCode,
phone: phone,
created_at: createdAt,
}).run();

const session = await lucia.createSession(userId, {});
appendHeader(event, "Set-Cookie", lucia.createSessionCookie(session.id).serialize());
return { success: true};
} catch (error) {
return { success: false, errors };
}
}

});
import { generateId } from "lucia";
import { user } from "@/server/db/schema.ts";

export default defineEventHandler(async (event) => {

const lucia = event.context.lucia;
const db = event.context.db;

const body = await readBody(event);

const {
firstname,
lastname,
email,
username,
password,
confirm_password,
country,
gender,
phone,
selectedPhoneCode,
date_of_birth,
terms
} = body;


try{
await db.insert(user).values({
id: userId,
firstname: firstname,
lastname: lastname,
email: email,
username: username,
password: password,
confirm_password: confirm_password,
country: country,
gender: gender,
date_of_birth: date_of_birth,
selectedPhoneCode: selectedPhoneCode,
phone: phone,
created_at: createdAt,
}).run();

const session = await lucia.createSession(userId, {});
appendHeader(event, "Set-Cookie", lucia.createSessionCookie(session.id).serialize());
return { success: true};
} catch (error) {
return { success: false, errors };
}
}

});
3 replies
NNuxt
Created by KWAC on 7/28/2024 in #❓・help
nuxt 3 + cloudfare D1 problems with env.d.ts file
@Oreki Sorry for pinging I now setup it correctly using command
npm create cloudflare@latest my-nuxt-app -- --framework=nuxt
npm create cloudflare@latest my-nuxt-app -- --framework=nuxt
I was missing some files like
worker-configuration.d
worker-configuration.d
Also I had to downgrade wrangler version because newer one was broken. My drizzle config looks like this:
import { defineConfig } from "drizzle-kit"

export default defineConfig({
dialect: 'sqlite',
schema: './server/db/schema.ts',
out: './server/db/migrations',
driver: 'd1-http',
dbCredentials: {
accountId: 'xxx',
databaseId: 'xxx',
token: 'xxx'
}
})
import { defineConfig } from "drizzle-kit"

export default defineConfig({
dialect: 'sqlite',
schema: './server/db/schema.ts',
out: './server/db/migrations',
driver: 'd1-http',
dbCredentials: {
accountId: 'xxx',
databaseId: 'xxx',
token: 'xxx'
}
})
My question is how to query and receive data from a table? Mine doesn't really work. I have two entries in that table. It shows status 200 but it doens't really print out that info from table getdata.js
import { defineEventHandler } from 'h3'
import { users } from '@/server/db/schema'
import { eq } from 'drizzle-orm'

export default defineEventHandler(async (event) => {
const db = event.context.db

try {

const allUsers = await db.select().from(users).all()
console.log('All Users:', allUsers)


return allUsers
} catch (error) {
// Handle any errors that might occur
console.error('Error retrieving users:', error) // Log the error message
throw createError({
statusCode: 500,
statusMessage: 'Internal Server Error'
})
}
})
import { defineEventHandler } from 'h3'
import { users } from '@/server/db/schema'
import { eq } from 'drizzle-orm'

export default defineEventHandler(async (event) => {
const db = event.context.db

try {

const allUsers = await db.select().from(users).all()
console.log('All Users:', allUsers)


return allUsers
} catch (error) {
// Handle any errors that might occur
console.error('Error retrieving users:', error) // Log the error message
throw createError({
statusCode: 500,
statusMessage: 'Internal Server Error'
})
}
})
22 replies
CDCloudflare Developers
Created by KWAC on 7/30/2024 in #workers-help
Error after running command - npx wrangler pages deploy dist/ error happens
In the
preset: cloudfare-pages
preset: cloudfare-pages
I used nitro-cloudfare-dev instead of cloudfare-pages but I suddenly started getting error with that (Cannot read properties of undefined (reading '$production'))
3 replies
CDCloudflare Developers
Created by KWAC on 7/30/2024 in #workers-help
Error after running command - npx wrangler pages deploy dist/ error happens
here's my nuxt.config.js
import { defineNuxtConfig } from 'nuxt/config'


export default defineNuxtConfig({
ssr: true,

nitro: {
preset: 'cloudflare-pages',
},

modules: [
'@nuxtjs/tailwindcss',
'@vuesax-alpha/nuxt',
'@nuxt/image',
'nuxt-gtag',
'nuxt-multi-tenancy',
],

multiTenancy: {
tenantDynamicRoute: 'site',
rootDomains: ["localhost:3000", "taskerdata.com"],
sites: ['worker', 'requester', 'blog']
},


gtag: {
id: 'G-KV3QMHHZJ4'
},

plugins: [
'~/plugins/loading.js',
'~/plugins/recaptcha.js'
],



image: {
dir: 'assets/images'
},

css: [
'/assets/css/main.css',
'/node_modules/flag-icons/css/flag-icons.min.css',
'/node_modules/vuesax-alpha/theme-chalk/vs-loading.css'
],



compatibilityDate: '2024-07-30',
})
import { defineNuxtConfig } from 'nuxt/config'


export default defineNuxtConfig({
ssr: true,

nitro: {
preset: 'cloudflare-pages',
},

modules: [
'@nuxtjs/tailwindcss',
'@vuesax-alpha/nuxt',
'@nuxt/image',
'nuxt-gtag',
'nuxt-multi-tenancy',
],

multiTenancy: {
tenantDynamicRoute: 'site',
rootDomains: ["localhost:3000", "taskerdata.com"],
sites: ['worker', 'requester', 'blog']
},


gtag: {
id: 'G-KV3QMHHZJ4'
},

plugins: [
'~/plugins/loading.js',
'~/plugins/recaptcha.js'
],



image: {
dir: 'assets/images'
},

css: [
'/assets/css/main.css',
'/node_modules/flag-icons/css/flag-icons.min.css',
'/node_modules/vuesax-alpha/theme-chalk/vs-loading.css'
],



compatibilityDate: '2024-07-30',
})
3 replies
NNuxt
Created by KWAC on 7/28/2024 in #❓・help
nuxt 3 + cloudfare D1 problems with env.d.ts file
And for MY_KV: KVNamespace is not needed in my case? As for now I only need D1
22 replies
NNuxt
Created by KWAC on 7/28/2024 in #❓・help
nuxt 3 + cloudfare D1 problems with env.d.ts file
Okay But looking at this import { CfProperties, Request, ExecutionContext, KVNamespace, D1Database } from '@cloudflare/workers-types'; declare module 'h3' { interface H3EventContext { cf: CfProperties, cloudflare: { request: Request, env: { MY_KV: KVNamespace, DB: D1Database, } context: ExecutionContext, }; } } am I declaring DB correctly?
DB: D1Database
DB: D1Database
22 replies
NNuxt
Created by KWAC on 7/28/2024 in #❓・help
nuxt 3 + cloudfare D1 problems with env.d.ts file
env.d.ts specifically needs to be in src->types folder? I thought i can paste this file in root folder of the project
22 replies
NNuxt
Created by KWAC on 7/28/2024 in #❓・help
nuxt 3 + cloudfare D1 problems with env.d.ts file
could you share a repo so i could take a look?
22 replies
NNuxt
Created by KWAC on 7/28/2024 in #❓・help
nuxt 3 + cloudfare D1 problems with env.d.ts file
eh unfortunately not, i'm still trying to figure out what could be wrong
22 replies
NNuxt
Created by KWAC on 7/28/2024 in #❓・help
nuxt 3 + cloudfare D1 problems with env.d.ts file
am i doing something wrong
22 replies
NNuxt
Created by KWAC on 7/28/2024 in #❓・help
nuxt 3 + cloudfare D1 problems with env.d.ts file
And here is middleware->auth.ts
import { verifyRequestOrigin } from "lucia"
import { initializeLucia } from "../utils/auth"
import type { User, Session } from "lucia"

let lucia: ReturnType<typeof initializeLucia>

export default defineEventHandler(async (event) => {
// CSRF protection
if (!isMethod(event, "GET")) {
const originHeader = getHeader(event, "Origin") ?? null
const hostHeader = getHeader(event, "Host") ?? null
if (
!originHeader ||
!hostHeader ||
!verifyRequestOrigin(originHeader, [hostHeader])
) {
return sendNoContent(event, 403)
}
}



const { DB } = event.context.cloudflare.env

if (!lucia) {
lucia = initializeLucia(DB)
}

event.context.lucia = lucia


const sessionId = getCookie(event, lucia.sessionCookieName) ?? null
if (!sessionId) {
event.context.session = null
event.context.user = null
return
}

const { session, user } = await lucia.validateSession(sessionId)
if (session && session.fresh) {
appendResponseHeader(
event,
"Set-Cookie",
lucia.createSessionCookie(session.id).serialize()
)
}
if (!session) {
appendResponseHeader(
event,
"Set-Cookie",
lucia.createBlankSessionCookie().serialize()
)
}

event.context.session = session
event.context.user = user
})

declare module "h3" {
interface H3EventContext {
user: User | null
session: Session | null
lucia: ReturnType<typeof initializeLucia>
}
}
import { verifyRequestOrigin } from "lucia"
import { initializeLucia } from "../utils/auth"
import type { User, Session } from "lucia"

let lucia: ReturnType<typeof initializeLucia>

export default defineEventHandler(async (event) => {
// CSRF protection
if (!isMethod(event, "GET")) {
const originHeader = getHeader(event, "Origin") ?? null
const hostHeader = getHeader(event, "Host") ?? null
if (
!originHeader ||
!hostHeader ||
!verifyRequestOrigin(originHeader, [hostHeader])
) {
return sendNoContent(event, 403)
}
}



const { DB } = event.context.cloudflare.env

if (!lucia) {
lucia = initializeLucia(DB)
}

event.context.lucia = lucia


const sessionId = getCookie(event, lucia.sessionCookieName) ?? null
if (!sessionId) {
event.context.session = null
event.context.user = null
return
}

const { session, user } = await lucia.validateSession(sessionId)
if (session && session.fresh) {
appendResponseHeader(
event,
"Set-Cookie",
lucia.createSessionCookie(session.id).serialize()
)
}
if (!session) {
appendResponseHeader(
event,
"Set-Cookie",
lucia.createBlankSessionCookie().serialize()
)
}

event.context.session = session
event.context.user = user
})

declare module "h3" {
interface H3EventContext {
user: User | null
session: Session | null
lucia: ReturnType<typeof initializeLucia>
}
}
Specifically this part
js const { DB } = event.context.cloudflare.env
js const { DB } = event.context.cloudflare.env
is responsible
22 replies