Ayush Goyal
Ayush Goyal
Explore posts from servers
TTCTheo's Typesafe Cult
Created by Ayush Goyal on 8/12/2024 in #questions
applying migrations...Error: getaddrinfo ENOTFOUND postgres
Hi Guys , I am using nextjs app router with drizzle with postgres and its working fine in development mode but when i am running it with docker compose up --build its giving me this error
[⣷] applying migrations...Error: getaddrinfo ENOTFOUND postgres
1.013 at /app/node_modules/pg-pool/index.js:45:11
1.013 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
1.013 at PgDialect.migrate (/app/node_modules/src/pg-core/dialect.ts:72:3)
1.013 at migrate (/app/node_modules/src/node-postgres/migrator.ts:10:2) {
1.013 errno: -3008,
1.013 code: 'ENOTFOUND',
1.013 syscall: 'getaddrinfo',
1.013 hostname: 'postgres'
1.013 }
[⣷] applying migrations...Error: getaddrinfo ENOTFOUND postgres
1.013 at /app/node_modules/pg-pool/index.js:45:11
1.013 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
1.013 at PgDialect.migrate (/app/node_modules/src/pg-core/dialect.ts:72:3)
1.013 at migrate (/app/node_modules/src/node-postgres/migrator.ts:10:2) {
1.013 errno: -3008,
1.013 code: 'ENOTFOUND',
1.013 syscall: 'getaddrinfo',
1.013 hostname: 'postgres'
1.013 }
the whole code can be found in this repo https://github.com/AyushiitrFreedom/bountpirac
2 replies
DTDrizzle Team
Created by Ayush Goyal on 8/12/2024 in #help
applying migrations...Error: getaddrinfo ENOTFOUND postgres
Hi Guys , I am using nextjs app router with drizzle with postgres and its working fine in development mode but when i am running it with docker compose up --build its giving me this error
[⣷] applying migrations...Error: getaddrinfo ENOTFOUND postgres
1.013 at /app/node_modules/pg-pool/index.js:45:11
1.013 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
1.013 at PgDialect.migrate (/app/node_modules/src/pg-core/dialect.ts:72:3)
1.013 at migrate (/app/node_modules/src/node-postgres/migrator.ts:10:2) {
1.013 errno: -3008,
1.013 code: 'ENOTFOUND',
1.013 syscall: 'getaddrinfo',
1.013 hostname: 'postgres'
1.013 }
[⣷] applying migrations...Error: getaddrinfo ENOTFOUND postgres
1.013 at /app/node_modules/pg-pool/index.js:45:11
1.013 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
1.013 at PgDialect.migrate (/app/node_modules/src/pg-core/dialect.ts:72:3)
1.013 at migrate (/app/node_modules/src/node-postgres/migrator.ts:10:2) {
1.013 errno: -3008,
1.013 code: 'ENOTFOUND',
1.013 syscall: 'getaddrinfo',
1.013 hostname: 'postgres'
1.013 }
the whole code can be found in this repo https://github.com/AyushiitrFreedom/bountpirac
1 replies
TTCTheo's Typesafe Cult
Created by Ayush Goyal on 9/1/2023 in #questions
React query Refetching on page change
let { data: orders, isLoading, isFetching, isError, error, refetch } = trpc.order.getallcart.useQuery(undefined, { retry: 1 });
let { data: orders, isLoading, isFetching, isError, error, refetch } = trpc.order.getallcart.useQuery(undefined, { retry: 1 });
I am using this code ( react query + trpc) , i want whenever i change links , router , the query should rerun and new data should come from the database but it is not happening , i tried various refetching methods but none of them worked , anyone who can suggest something
3 replies
TtRPC
Created by Ayush Goyal on 8/29/2023 in #❓-help
TRPC retries with new app dir
let { data: name, isLoading, isFetching, isError, error } = trpc.home.home.useQuery();
let { data: name, isLoading, isFetching, isError, error } = trpc.home.home.useQuery();
I am using React query with App directory in next js , can somebody tell me how can i aplly retry:1 , because by default it is set to 3
2 replies
TtRPC
Created by Ayush Goyal on 8/29/2023 in #❓-help
opts.input is of type undifined
register: publicProcedure.input(
RegisterSchema
).mutation(async (opts) => {
//checking for existing user
const existingUser = await db.select().from(user).where(eq(user.email, opts.input.email));
register: publicProcedure.input(
RegisterSchema
).mutation(async (opts) => {
//checking for existing user
const existingUser = await db.select().from(user).where(eq(user.email, opts.input.email));
RegisterSchema is a zod schema comming from an another file it is giving me the error opts.input is of type undefined
2 replies
TTCTheo's Typesafe Cult
Created by Ayush Goyal on 8/19/2023 in #questions
TrPC + Express + Next 13
src/app/api/trpc/[trpc]/route.ts
import {
FetchCreateContextFnOptions,
fetchRequestHandler,
} from "@trpc/server/adapters/fetch";
import { appRouter } from "../trpc-router";

const handler = (request: Request) => {
console.log(`incoming request ${request.url}`);
return fetchRequestHandler({
endpoint: "/api/trpc",
req: request,
router: appRouter,
createContext: function (
opts: FetchCreateContextFnOptions
): object | Promise<object> {
return {};
},
});
};

export { handler as GET, handler as POST };
import {
FetchCreateContextFnOptions,
fetchRequestHandler,
} from "@trpc/server/adapters/fetch";
import { appRouter } from "../trpc-router";

const handler = (request: Request) => {
console.log(`incoming request ${request.url}`);
return fetchRequestHandler({
endpoint: "/api/trpc",
req: request,
router: appRouter,
createContext: function (
opts: FetchCreateContextFnOptions
): object | Promise<object> {
return {};
},
});
};

export { handler as GET, handler as POST };
This is the way you add trpc to Next13 , but how can i achieve this if i am using Express js in my backend
3 replies
TTCTheo's Typesafe Cult
Created by Ayush Goyal on 8/11/2023 in #questions
Trpc google authentication passport
const GoogleAuth = middleware(async (opts) => {
passport.authenticate('google', { failureRedirect: '/login', successRedirect: '/protected' })
return opts.next()
});

google: googleProcedure.query(async (opts) => {
console.log(opts);
}),
const GoogleAuth = middleware(async (opts) => {
passport.authenticate('google', { failureRedirect: '/login', successRedirect: '/protected' })
return opts.next()
});

google: googleProcedure.query(async (opts) => {
console.log(opts);
}),
I am using passport js but i don't know why my code is not working like its not taking me to google signup
2 replies
DTDrizzle Team
Created by Ayush Goyal on 8/10/2023 in #help
how to make a session using drizzle
import express from 'express';
import session from 'express-session';
import genFunc from 'connect-pg-simple';

const PostgresqlStore = genFunc(session);
const sessionStore = new PostgresqlStore({
conString: '<insert-connection-string-here>',
});

const app = express();
app.use(express.json());

app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: false,
cookie: cookieOptions, // define cookieOptions
store: sessionStore
}));
import express from 'express';
import session from 'express-session';
import genFunc from 'connect-pg-simple';

const PostgresqlStore = genFunc(session);
const sessionStore = new PostgresqlStore({
conString: '<insert-connection-string-here>',
});

const app = express();
app.use(express.json());

app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: false,
cookie: cookieOptions, // define cookieOptions
store: sessionStore
}));
this is how we make a session using postgress , i wanted to know how will we do that using drizzle-postgress
1 replies
TTCTheo's Typesafe Cult
Created by Ayush Goyal on 8/9/2023 in #questions
Typescript with jwt passport
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt';
import passport from 'passport';

const opts = {};


opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = 'Random string';

passport.use(new JwtStrategy(opts, function (jwt_payload, done) {
UserModel.findOne({ id: jwt_payload.id }, function (err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
// or you could create a new account
}
});
}));
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt';
import passport from 'passport';

const opts = {};


opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = 'Random string';

passport.use(new JwtStrategy(opts, function (jwt_payload, done) {
UserModel.findOne({ id: jwt_payload.id }, function (err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
// or you could create a new account
}
});
}));
I have this code with me , how do i write in typescript , what do you guys do . I know typescript but i feel that there are many places i will miss typesafety
2 replies
TTCTheo's Typesafe Cult
Created by Ayush Goyal on 8/8/2023 in #questions
how to access Nested routes
export const appRouter = t.router({
show: t.procedure.query(async () => {
const cities: Cities[] = await db.select().from(city);
return cities;
}),

auth: authRouter,
})
export const appRouter = t.router({
show: t.procedure.query(async () => {
const cities: Cities[] = await db.select().from(city);
return cities;
}),

auth: authRouter,
})
export const authRouter = t.router({
log: t.procedure.query(async () => {
const cities: Cities[] = await db.select().from(city);
return cities;
})

})
export const authRouter = t.router({
log: t.procedure.query(async () => {
const cities: Cities[] = await db.select().from(city);
return cities;
})

})
when i visit localhost:5000/show , it works but when i visit localhost:5000/auth/log , it does not work anyone who can help me ?
2 replies
TtRPC
Created by Ayush Goyal on 7/27/2023 in #❓-help
what is "use" keyword
const baseProcedure = t.procedure
.input(z.object({ townName: z.string() }))
.use((opts) => {
const input = opts.input;

const input: {
townName: string;
}

console.log(`Handling request with user from: ${input.townName}`);

return opts.next();
});
const baseProcedure = t.procedure
.input(z.object({ townName: z.string() }))
.use((opts) => {
const input = opts.input;

const input: {
townName: string;
}

console.log(`Handling request with user from: ${input.townName}`);

return opts.next();
});
what is this usekeyword any place i can read about it
5 replies
DTDrizzle Team
Created by Ayush Goyal on 7/17/2023 in #help
Anyone who can give a example of this
1 replies
TtRPC
Created by Ayush Goyal on 6/10/2023 in #❓-help
What is error formating
I understand error handeling but what is error formating , found it in trcp docs have'nt seen that thing before
3 replies
TtRPC
Created by Ayush Goyal on 6/10/2023 in #❓-help
where does opts.path and opts.type came from ? i guess by default it only stores ctx ,next and input
const loggerMiddleware = middleware(async (opts) => {
const start = Date.now();
 
const result = await opts.next();
 
const durationMs = Date.now() - start;
const meta = { path: opts.path, type: opts.type, durationMs };
 
result.ok
? console.log('OK request timing:', meta)
: console.error('Non-OK request timing', meta);
 
return result;
});
 
export const loggedProcedure = publicProcedure.use(loggerMiddleware);
const loggerMiddleware = middleware(async (opts) => {
const start = Date.now();
 
const result = await opts.next();
 
const durationMs = Date.now() - start;
const meta = { path: opts.path, type: opts.type, durationMs };
 
result.ok
? console.log('OK request timing:', meta)
: console.error('Non-OK request timing', meta);
 
return result;
});
 
export const loggedProcedure = publicProcedure.use(loggerMiddleware);
the code is from middleware documentation
4 replies
TtRPC
Created by Ayush Goyal on 6/10/2023 in #❓-help
Passing objects to the next() function of the middle ware
// -------------------------------------------------
// @filename: context.ts
// -------------------------------------------------
import type { inferAsyncReturnType } from '@trpc/server';
import type { CreateNextContextOptions } from '@trpc/server/adapters/next';
import { getSession } from 'next-auth/react';
 
/**
* Creates context for an incoming request
* @link https://trpc.io/docs/context
*/
export async function createContext(opts: CreateNextContextOptions) {
const session = await getSession({ req: opts.req });
 
return {
session,
};
}
 
export type Context = inferAsyncReturnType<typeof createContext>;
 
// -------------------------------------------------
// @filename: trpc.ts
// -------------------------------------------------
import { initTRPC, TRPCError } from '@trpc/server';
import { Context } from './context';
 
const t = initTRPC.context<Context>().create();
 
const isAuthed = t.middleware(({ next, ctx }) => {
if (!ctx.session?.user?.email) {
throw new TRPCError({
code: 'UNAUTHORIZED',
});
}
return next({
ctx: {
// Infers the `session` as non-nullable
session: ctx.session,
},
});
});
 
export const middleware = t.middleware;
export const router = t.router;
 
/**
* Unprotected procedure
*/
export const publicProcedure = t.procedure;
 
/**
* Protected procedure
*/
export const protectedProcedure = t.procedure.use(isAuthed);
// -------------------------------------------------
// @filename: context.ts
// -------------------------------------------------
import type { inferAsyncReturnType } from '@trpc/server';
import type { CreateNextContextOptions } from '@trpc/server/adapters/next';
import { getSession } from 'next-auth/react';
 
/**
* Creates context for an incoming request
* @link https://trpc.io/docs/context
*/
export async function createContext(opts: CreateNextContextOptions) {
const session = await getSession({ req: opts.req });
 
return {
session,
};
}
 
export type Context = inferAsyncReturnType<typeof createContext>;
 
// -------------------------------------------------
// @filename: trpc.ts
// -------------------------------------------------
import { initTRPC, TRPCError } from '@trpc/server';
import { Context } from './context';
 
const t = initTRPC.context<Context>().create();
 
const isAuthed = t.middleware(({ next, ctx }) => {
if (!ctx.session?.user?.email) {
throw new TRPCError({
code: 'UNAUTHORIZED',
});
}
return next({
ctx: {
// Infers the `session` as non-nullable
session: ctx.session,
},
});
});
 
export const middleware = t.middleware;
export const router = t.router;
 
/**
* Unprotected procedure
*/
export const publicProcedure = t.procedure;
 
/**
* Protected procedure
*/
export const protectedProcedure = t.procedure.use(isAuthed);
i never knew if one can pass arguments to the next() function , my doubt is why are we passing them and how do we use them
4 replies
TtRPC
Created by Ayush Goyal on 6/10/2023 in #❓-help
opts object passed to mutation , i can not understand where it came from
export const authorizedProcedure = publicProcedure
.input(z.object({ townName: z.string() }))
.use((opts) => {
if (opts.input.townName !== 'Pucklechurch') {
throw new TRPCError({
code: 'FORBIDDEN',
message: "We don't take kindly to out-of-town folk",
});
}
 
return opts.next();
});
 
export const appRouter = t.router({
hello: authorizedProcedure.query(() => {
return {
message: 'hello world',
};
}),
goodbye: authorizedProcedure.mutation(async (opts) => {
await opts.ctx.signGuestBook();
 
return {
message: 'goodbye!',
};
}),
});
export const authorizedProcedure = publicProcedure
.input(z.object({ townName: z.string() }))
.use((opts) => {
if (opts.input.townName !== 'Pucklechurch') {
throw new TRPCError({
code: 'FORBIDDEN',
message: "We don't take kindly to out-of-town folk",
});
}
 
return opts.next();
});
 
export const appRouter = t.router({
hello: authorizedProcedure.query(() => {
return {
message: 'hello world',
};
}),
goodbye: authorizedProcedure.mutation(async (opts) => {
await opts.ctx.signGuestBook();
 
return {
message: 'goodbye!',
};
}),
});
here in goodbye route , where does the opts object come from , in authorized proccesor middleware , i get it otps come from the input but in goodbye i am not able to understand where opts come from , maybe
return opts.next();
return opts.next();
passes it to the goodbye route
5 replies