Lautaro_dapin
Lautaro_dapin
Explore posts from servers
TtRPC
Created by Lautaro_dapin on 12/10/2023 in #❓-help
Discriminated output based on discrimiated input
I have this function which works correctly by itself, but when i put it on trpc, the output doesn't get inffered correctly based o the input
type GetFarmsInput = {
growerId?: number;
provider?: string;
leafUserId?: string;
page?: number;
size?: number;
} & ({withFields: true} | {withFields?: false | undefined});

type GetFarmsOutput<T extends GetFarmsInput> = T extends {withFields: true}
? FarmSchema[]
: (FarmSchema & {fields: FieldSchema[]})[];

export async function getFarms<T extends GetFarmsInput>(input: T): Promise<GetFarmsOutput<T>>;
export async function getFarms<T extends GetFarmsInput>(input: T) {
const {withFields, ...options} = input;
const searchParams = stringify(options);
const response = await endpoint(`/services/fields/api/farms?${searchParams.toString()}`, 'GET');
if (!response.ok) {
throw Error(`Couldn't get the farms`, {cause: await response.json()});
}
const farms = await farmsSchema.parseAsync(await response.json());
if (withFields) {
return await Promise.all(
farms.map(async (farm) => {
const fieldsMap = mapToIds(
await getAllFields({farmId: farm.id, size: 100, leafUserId: options.leafUserId})
);
return {
...farm,
fields: farm.fieldIds.map((id) => fieldsMap.get(id)),
};
})
);
}
return farms;
}
type GetFarmsInput = {
growerId?: number;
provider?: string;
leafUserId?: string;
page?: number;
size?: number;
} & ({withFields: true} | {withFields?: false | undefined});

type GetFarmsOutput<T extends GetFarmsInput> = T extends {withFields: true}
? FarmSchema[]
: (FarmSchema & {fields: FieldSchema[]})[];

export async function getFarms<T extends GetFarmsInput>(input: T): Promise<GetFarmsOutput<T>>;
export async function getFarms<T extends GetFarmsInput>(input: T) {
const {withFields, ...options} = input;
const searchParams = stringify(options);
const response = await endpoint(`/services/fields/api/farms?${searchParams.toString()}`, 'GET');
if (!response.ok) {
throw Error(`Couldn't get the farms`, {cause: await response.json()});
}
const farms = await farmsSchema.parseAsync(await response.json());
if (withFields) {
return await Promise.all(
farms.map(async (farm) => {
const fieldsMap = mapToIds(
await getAllFields({farmId: farm.id, size: 100, leafUserId: options.leafUserId})
);
return {
...farm,
fields: farm.fieldIds.map((id) => fieldsMap.get(id)),
};
})
);
}
return farms;
}
2 replies
TTCTheo's Typesafe Cult
Created by Lautaro_dapin on 10/2/2023 in #questions
Database migrations
Is there any tool to create migrations with typescript script support? like django or alembic has?? I only found kysely, which has a migration system but you still have to write your own migrations, which seem pretty stupid due to the fact that you have all the types to make it automagically
9 replies
TtRPC
Created by Lautaro_dapin on 6/11/2023 in #❓-help
Optimistic update on infinite query
Node 18.12.1 with pnpm trpc v 10.28.1 I have the following query to render a list of posts
// List of posts
export default function ListPage(){
const router = useRouter()
const q = router.query.q as string || ''
const {data} = api.post.feed.useInfiniteQuery({q}, {
getNextPageParam: lastPage => lastPage.nextCursor,
})
const posts = data?.pages.flatMap(page => page.items)

return (
<>
{posts.map(post => <Post post={post}/> )}
</>
)
}
// List of posts
export default function ListPage(){
const router = useRouter()
const q = router.query.q as string || ''
const {data} = api.post.feed.useInfiniteQuery({q}, {
getNextPageParam: lastPage => lastPage.nextCursor,
})
const posts = data?.pages.flatMap(page => page.items)

return (
<>
{posts.map(post => <Post post={post}/> )}
</>
)
}
Then inside the Post component i have the following muutation to toggle a like server state But for some reason when i want to update the cache for an optimistic update the cache is always empty, idk why
const utils = api.useContext()
const toggleLikeMutation = api.post.toggleLikePost.useMutation({
onMutate: async () => {
const snapshot = utils.post.feed.getInfiniteData({q: ''})
console.log({snapshot}) // <---- EMPTY
if (!snapshot) return {snapshot}
utils.post.feed.setInfiniteData({}, () => {
return {
...snapshot,
pages: snapshot.pages.map(page => {
return {
...page,
items: page.items.map(post => {
if (post.id !== id) return post
return {
...post,
liked: !post.liked
}
})
}
})
}
})
return {
snapshot
}
},

onError: (error, {postId}, ctx) => {
ctx?.snapshot && utils.post.feed.setInfiniteData({}, () => ctx.snapshot)
},

async onSuccess() {
await utils.post.feed.invalidate()

}
})
const utils = api.useContext()
const toggleLikeMutation = api.post.toggleLikePost.useMutation({
onMutate: async () => {
const snapshot = utils.post.feed.getInfiniteData({q: ''})
console.log({snapshot}) // <---- EMPTY
if (!snapshot) return {snapshot}
utils.post.feed.setInfiniteData({}, () => {
return {
...snapshot,
pages: snapshot.pages.map(page => {
return {
...page,
items: page.items.map(post => {
if (post.id !== id) return post
return {
...post,
liked: !post.liked
}
})
}
})
}
})
return {
snapshot
}
},

onError: (error, {postId}, ctx) => {
ctx?.snapshot && utils.post.feed.setInfiniteData({}, () => ctx.snapshot)
},

async onSuccess() {
await utils.post.feed.invalidate()

}
})
2 replies
DTDrizzle Team
Created by Lautaro_dapin on 6/6/2023 in #help
Sveltekit Failed to resolve import "cloudflare:sockets"
I was trying to use drizzle orm in a sveltekit project with postgres run in a docker container, but i'm having the following error
[plugin:vite:import-analysis] Failed to resolve import "cloudflare:sockets" from "node_modules\.vite\deps\chunk-JJ5CRB2A.js?v=dcae3c33". Does the file exist?
F:/Python/jira-clon-2/node_modules/.vite/deps/chunk-JJ5CRB2A.js:2908:44
2906| this.once("connect", connectListener);
2907| const options = this.ssl ? { secureTransport: "starttls" } : {};
2908| const { connect } = await import("cloudflare:sockets");
| ^
2909| this._cfSocket = connect(`${host}:${port}`, options);
2910| this._cfWriter = this._cfSocket.writable.getWriter();
[plugin:vite:import-analysis] Failed to resolve import "cloudflare:sockets" from "node_modules\.vite\deps\chunk-JJ5CRB2A.js?v=dcae3c33". Does the file exist?
F:/Python/jira-clon-2/node_modules/.vite/deps/chunk-JJ5CRB2A.js:2908:44
2906| this.once("connect", connectListener);
2907| const options = this.ssl ? { secureTransport: "starttls" } : {};
2908| const { connect } = await import("cloudflare:sockets");
| ^
2909| this._cfSocket = connect(`${host}:${port}`, options);
2910| this._cfWriter = this._cfSocket.writable.getWriter();
7 replies
TTCTheo's Typesafe Cult
Created by Lautaro_dapin on 2/17/2023 in #questions
Middleware doesn't load the `server.mjs` variables
I have the followinng middleware in src/middleware.ts
import {NextRequest, NextResponse} from 'next/server'
import {env} from 'src/env/server.mjs'

// This function can be marked `async` if using `await` inside
export function middleware(req: NextRequest) {
if (!['_next', 'favicon.icon', 'assets'].some(c => req.nextUrl.pathname.includes(c))) {
console.info('Match the path', req.url, req.nextUrl.pathname)
}

return NextResponse.next()
}

// See "Matching Paths" below to learn more
export const config = {
matcher: [
'/',
'/((?!api|_next/static|_next/image|favicon.ico).*)',
'/((?!users/login|users/register|users/forgot|users/activation|users/register).*)',
],

}
import {NextRequest, NextResponse} from 'next/server'
import {env} from 'src/env/server.mjs'

// This function can be marked `async` if using `await` inside
export function middleware(req: NextRequest) {
if (!['_next', 'favicon.icon', 'assets'].some(c => req.nextUrl.pathname.includes(c))) {
console.info('Match the path', req.url, req.nextUrl.pathname)
}

return NextResponse.next()
}

// See "Matching Paths" below to learn more
export const config = {
matcher: [
'/',
'/((?!api|_next/static|_next/image|favicon.ico).*)',
'/((?!users/login|users/register|users/forgot|users/activation|users/register).*)',
],

}
But i get the zod error because the serverSchema fails the parse.
❌ Invalid environment variables:
DATABASE_URL: Required
NODE_ENV: Required
❌ Invalid environment variables:
DATABASE_URL: Required
NODE_ENV: Required
9 replies
TTCTheo's Typesafe Cult
Created by Lautaro_dapin on 11/23/2022 in #questions
T3 Stacks requires internet?
Does tRCP requires internet connection for been used? I was in the field without internet conection and the requests to the backend tRCP were not been executed
6 replies