code for https://youtu.be/I6ypD7qv3Z8
benawad / lireddit Goto Github PK
View Code? Open in Web Editor NEWHome Page: https://youtu.be/I6ypD7qv3Z8
License: MIT License
Home Page: https://youtu.be/I6ypD7qv3Z8
License: MIT License
code for https://youtu.be/I6ypD7qv3Z8
Hey Ben.
thanks a lot for the tutorial, I have been learning a lot from it.
I am running a windows machine and I couldn't use redis on it. So, i used connect-mongo middleware with express-session. Issue is I can see them getting stored in database but can't see them in browser. They are not getting stored in browser.
After redirecting from the login/register pages to the homepage, useMeQuery() does not run, it only runs after reloading from browser.
This is my navbar code:
export const Navbar: React.FC<NavbarProps> = ({}) => {
const [{ data, fetching }] = useMeQuery();
let body = null;
console.log(data);
console.log(fetching);
const router = useRouter();
if (fetching) {
// Data is loading
body = null;
} else if (!data?.me) {
// Not logged in
body = (
<div className="ml-auto flex">
<Link href="/login">
<div className="mr-2 cursor-pointer hover:underline">Login</div>
</Link>
<Link href="/register">
<div className="cursor-pointer hover:underline">Register</div>
</Link>
</div>
);
} else {
// Logged in
body = <div className="ml-auto">Hello, {data.me.username}</div>;
}
return <div className="flex bg-gray-500 p-4">{body}</div>;
};
Not sure if it matters, but I am using router.push to redirect. I've tried router.replace but that won't work either.
Thanks!
Deploying the dokku app (running dokku tags:deploy api latest
) raised this error:
Attempting pre-flight checks (web.1) Waiting for 10 seconds ... ee21cdf0ef4d125ec6f443e7cdb732f4dcb97e31086c2361d8c69287d3d05a57 App container failed to start!! =====> api web container output: [FATAL tini (6)] exec docker-entrypoint.sh failed: Exec format error =====> end api web container output
This is with Redis 6.2.6. Some searching led me to believe that the docker container's connection to redis is the culprit.
In the .env file, I changed REDIS_URL to:
REDIS_URL= redis://:[email protected]:6379
But this results in an authentication error from Redis. Using host.docker.internal without a password leads to a NOAUTH error.
Has anyone experienced a similar issue? I am considering following the instructions here: redis/ioredis#763 to deploy using docker-compose, since it seems like the docker Redis container is not playing nicely with the backend.
Thanks
Hello Ben, I am a newbie to react and after creating createUrqlClient.ts file and copy the cacheExcange
from _app.tsx, then removing all the unnecessary imports from _app.tsx and exporting the index like this export default withUrqlClient(createUrqlClient)(Index)
in index.tsx file, I am getting the error below,
Default Client: No client has been specified using urql's Provider.This means that urql will be falling back to defaults including making requests to `/
graphql`.
If that's not what you want, please create a client and add a Provider.
How can i solve this issue?
I just follow your tutorials,I set the url: "http://localhost:4000/graphql"
, but the browser can't found the server. here is my createUrqlClient.js
snippet, Is there any setting to add ?
export const createUrqlClient = (ssrExchange: any) => ({
url: "http://localhost:4000/graphql",
fetchOptions: {
credentials: "include" as const,
},
exchanges: [
dedupExchange,
cacheExchange({
...
}),
ssrExchange,
fetchExchange,
],
});
Hi Ben,
Thank you so much for this tutorial.
If any one can help me I would really appreciate it
I have been stuck on this part for over two days. Any time I add in line 141 I get the error below in my sandbox . I have also added in a screen shot from my types file. I also do not see any cookie being set. I f I remove line 141 I do not get an error it logs me in but still does not set a cookie.
Thanks for any help!
Thanks for that great course, got to learn quite a lot.
Should we configure these env variables in dokku while deploying?
App container failed to start!!
/usr/src/app/node_modules/dotenv-safe/index.js:31
throw new MissingEnvVarsError(allowEmptyValues, options.path || '.env', example, missing, dotenvResult.error);
^
MissingEnvVarsError: The following variables were defined in .env.example but are not present in the environment:
DATABASE_URL
Make sure to add them to .env or directly to the environment.
If you expect any of these variables to be empty, you can use the allowEmptyValues option:
require('dotenv-safe').config({
allowEmptyValues: true
});
at Object.config (/usr/src/app/node_modules/dotenv-safe/index.js:31:19)
at /usr/src/app/node_modules/dotenv-safe/config.js:9:18
at Object.<anonymous> (/usr/src/app/node_modules/dotenv-safe/config.js:10:3)
at Module._compile (internal/modules/cjs/loader.js:1076:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:941:32)
at Function.Module._load (internal/modules/cjs/loader.js:782:14)
at Module.require (internal/modules/cjs/loader.js:965:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (/usr/src/app/dist/index.js:18:1) {
missing: [ 'DATABASE_URL' ],
sample: '.env.example',
example: '.env.example'
}
I kept getting CORS errors when GraphQL Code Generator tries to load the schema. In the end I solved the issue by adding Origin: 'http://localhost:3000'
to the schema request headers so my codegen.yml
file looks like this:
overwrite: true
schema:
- 'http://localhost:4000/graphql':
headers:
Origin: 'http://localhost:3000'
documents: 'src/graphql/**/*.graphql'
generates:
src/generated/graphql.tsx:
plugins:
- 'typescript'
- 'typescript-operations'
- 'typescript-urql'
Does anyone know a better solution?
lireddit/server/src/resolvers/post.ts
Line 138 in 5d857b8
Should this line be replacements.push(cursor) ?
I don't think ParseInt and Date are helping here. Using those functions turns the string into a date close to the beginning of time according to Unix. No extra posts will be retrieved when createdAt is set to this date.
Problem running 'yarn gen' after installing codegen @ 3:13 h.
src/generated/graphql.tsx
Error: Cannot use GraphQLObjectType "FieldError" from another module or realm.
Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.
https://yarnpkg.com/en/docs/selective-version-resolutions
Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.
running codegen.yml
overwrite: true
schema: "http://localhost:4001/graphql"
documents: "src/graphql/**/*.graphql"
generates:
src/generated/graphql.tsx:
plugins:
- "typescript"
- "typescript-operations"
- "typescript-urql"
I think i had conflicting packages. Removing "urql", which i think caused the problem, and reinstalling it solved the error.
yarn run v1.22.17
$ graphql-codegen --config codegen.yml
√ Parse configuration
√ Generate outputs
with package.json
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"gen": "graphql-codegen --config codegen.yml"
},
"dependencies": {
"@chakra-ui/icons": "^1.0.0",
"@chakra-ui/react": "^1.8.5",
"@emotion/react": "^11.0.0",
"@emotion/styled": "^11.0.0",
"formik": "^2.2.9",
"framer-motion": "^4.0.3",
"next": "latest",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"graphql": "^16.3.0",
"urql": "^2.2.0"
},
"devDependencies": {
"@graphql-codegen/cli": "^2.6.2",
"@graphql-codegen/typescript": "2.4.5",
"@graphql-codegen/typescript-operations": "2.3.2",
"@graphql-codegen/typescript-urql": "^3.5.3",
"@graphql-codegen/urql-introspection": "^2.1.1",
"@types/node": "^17.0.21",
"graphql-tag": "^2.12.6",
"typescript": "^4.5.5"
}
}
You can edit your package.json as needed. Delete the file 'yarn.lock', 'package-lock.json' and the folder 'node_modules' to clear your dependencies. And run 'npm install' / 'yarn install' to reinstall your dependencies.
I'm in minute 11:36:00 of the tutorial, and I noticed that findById was deprecated when implementing the createUserLoader function. I was able to get around it by doing the following:
export const createUserLoader = () =>
new DataLoader<number, Users>(async (userIds) => {
const users = await Users.findBy({ id: In(userIds as number[]) })
const userIdToUser: Record<number, Users> = {}
users.forEach((u) => {
userIdToUser[u.id] = u
})
const sortedUsers = userIds.map((userId) => userIdToUser[userId])
return sortedUsers
})
As you can see I used findBy
instead of findByIds
and the In
function provided by typeorm. I tried using the same approach for the createUpdootLoader, but I noticed that it did not work since I needed to search for both the userId
and the postId
to retrieve the corresponding upvotes. Was anyone able to implement that correctly? I am unsure how to use findBy
to search multiple fields with the keys since I cannot seem to separate the key fields by using keys.userId
and keys.postId
. This is my current code:
export const createUpdootLoader = () =>
new DataLoader<{ postId: number; userId: number }, Updoot | null>(
async (keys) => {
console.log('keys:', keys)
const updoots = await Updoot.findby({userId: In(keys as any} )
const updootIdsToUpdoot: Record<string, Upvotes> = {}
updoots.forEach((updoot) => {
upvoteIdsToUpvote[`${updoot.userId} | ${updoot.postId}`] = updoot
})
const sortedUpdoot = keys.map(
(key) => updootIdsToUpdoot[`${key.userId} | ${key.postId}`],
)
return sortedUpdoots
},
So, I am having this problem. Whenever I "login" using the GraphQL playground queries. It creates a cookie. But always throws the error -
ReplyError: ERR wrong number of arguments for 'set' command
And then when I try to run "me" in GraphQL playground. It never returns my user's data. It always Returns null
Any possible fixes?
I'm following the tutorial and i'm about 4 hours in, and I notice that whenever i try to get the me
query, my req.session never has a userId
field.
I'm clearly setting req.session.userId
everytime i login or register, and yet it doesn't get registered.
Here's a log showing req.session
during login and inside me query:
[query] select "e0".* from "post" as "e0" [took 4 ms]
[query] select "e0".* from "user" as "e0" where "e0"."username" = 'tushar' limit 1 [took 5 ms]
Login session: Session {
cookie: {
path: '/',
_expires: 2030-10-02T17:16:53.696Z,
originalMaxAge: 315360000000,
httpOnly: true,
secure: false,
sameSite: 'lax'
},
userId: 1
}
session: Session {
cookie: {
path: '/',
_expires: 2030-10-02T17:58:59.372Z,
originalMaxAge: 315360000000,
httpOnly: true,
sameSite: 'lax',
secure: false
}
}
[query] select "e0".* from "post" as "e0" [took 6 ms]
My code is present here: https://github.com/tusharsadhwani/lireddit
Thanks for the great tutorial.
I tried to replicate your tutorial. But confused a bit and I would appreciate a bit of help.
I have 2 entities: user
and productSubscription
inside product subscription entity:
@Field()
@Column()
userId: string
// relations
@Field(type => User)
@ManyToOne(() => User, user => user.productSubscriptions)
user: User
and user entity looks like:
// RELATIONS
@OneToMany(() => ProductSubscription, productSubscription => productSubscription.owner)
productSubscriptions: ProductSubscription[]
But when I'm trying to add a new product subscription I'm getting an error:
"insert or update on table \"product_subscription\" violates foreign key constraint \"FK_26ad2ed28449283180386eece95\"",
If I remove userId: string
column from productSubscription
and set user object (not just ID as you do) everything is working grate.
What I'm missing?
I am getting this warning on client side, probably some react hydration issue. searched for a while everywhere but could not find any solution. Would be nice you address this issue.
There is a small bug in deploy.sh
I believe.
By using the deploy script I was running into an issue where the app didnt deploy. After debugging I noticed in the end of your command for deploying the api you wrote: dokku deploy api $VERSION
. However I think this should be changed to dokku tags:deploy api $VERSION
.
When installing Redis @ 1:41h and testing the auth cookie, graphql will crash. This is because the new version of Redis (v4) doesn't support the code from the tuturial. The codeblock below will fix this. You can find the full documentation here: https://www.npmjs.com/package/connect-redis
const session = require("express-session");
let RedisStore = require("connect-redis")(session);
const main = async () => {
const orm = await MikroORM.init(microConfig);
await orm.getMigrator().up();
const { createClient } = require("redis");
let redisClient = createClient({ legacyMode: true });
redisClient.on("connect", () => console.log("Connected to Redis!"));
redisClient.on("error", (err: Error) =>
console.log("Redis Client Error", err)
);
redisClient.connect();
const app = express();
app.use(
session({
name: "qid",
store: new RedisStore({
client: redisClient,
disableTouch: true,
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 365 * 1, // 1 year
httpOnly: true,
sameSite: "lax",
secure: __prod__, // cookie only works in https
},
saveUninitialized: false,
secret: "bruhhhh",
resave: false,
})
);
Hi @benawad thanks for the great video I ran into a problem at around 2:51:16 if anybody can help me out that would be great thanks
btw I tried deleting the node modules and reinstalling them but it still doesn't work
yarn gen
it gives the following erroryarn run v1.22.10
$ graphql-codegen --config codegen.yml
√ Parse configuration
Generate outputs
> Generate src/generated/graphql.tsx
√ Load GraphQL schemas
√ Load GraphQL documents
× Generate
→ Unable to find template plugin matching typescript-urql
Found 1 error
✖ src/generated/graphql.tsx
Unable to find template plugin matching 'typescript-urql'
Install one of the following packages:
- @graphql-codegen/typescript-urql
- @graphql-codegen/typescript-urql-template
- @graphql-codegen/typescript-urql-plugin
- graphql-codegen-typescript-urql
- graphql-codegen-typescript-urql-template
- graphql-codegen-typescript-urql-plugin
- codegen-typescript-urql
- codegen-typescript-urql-template
- typescript-urql
Error: Unable to find template plugin matching typescript-urql
at getPluginByName (C:\Users\shash\Desktop\Dev Company\reddit-clone\node_modules\@graphql-codegen\cli\bin.js:335:11)
at async Promise.all (index 2)
at async C:\Users\shash\Desktop\Dev Company\reddit-clone\node_modules\@graphql-codegen\cli\bin.js:895:60
at async Task.task (C:\Users\shash\Desktop\Dev Company\reddit-clone\node_modules\@graphql-codegen\cli\bin.js:727:17)
Error: Unable to find template plugin matching typescript-urql
at getPluginByName (C:\Users\shash\Desktop\Dev Company\reddit-clone\node_modules\@graphql-codegen\cli\bin.js:335:11)
at async Promise.all (index 2)
at async C:\Users\shash\Desktop\Dev Company\reddit-clone\node_modules\@graphql-codegen\cli\bin.js:895:60
at async Task.task (C:\Users\shash\Desktop\Dev Company\reddit-clone\node_modules\@graphql-codegen\cli\bin.js:727:17)
Something went wrong
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Hello. In NavBar.tsx, in this hook: const [{ data, fetching }] = useMeQuery({pause: isServer()});
pause thing seems to cause expected HTML to contain a <div></div>...
warning. Is there any way to get rid of this warning? I asked on Stack Overflow: https://stackoverflow.com/questions/67256421/is-there-any-way-to-suppress-hydration-warning-in-react-fc, and there is one answer about server and client pause should be the same, but this solution works weird for me.
Hello. In user.ts (user resolver) register function is catching and handling error with code 23505:
try {
...
} catch (err) {
//|| err.detail.includes("already exists")) {
// duplicate username error
if (err.code === "23505") {
return {
errors: [
{
field: "username",
message: "username already taken",
},
],
};
}
}
But if you try to enter an e-mail that already exists in DB, it sends the same err code (23505) and detail field is similar to username error. key "(email)[email protected]" already exists.
So I think it's correct to check if it includes 'email' or 'username' in it.
if (err.code === "23505") {
if (err.detail.includes("email")){
return {
errors: [
{
field: "email",
message: "email already taken",
},
],
};
}
return {
errors: [
{
field: "username",
message: "username already taken",
},
],
};
When trying to create the new InputOrTextArea, following ben's code, it leads to some typescript errors.
Code:
let InputOrTextArea = Input;
if(textarea){
InputOrTextArea = Textarea;
}
Error:
let InputOrTextArea: ComponentWithAs<"input", InputProps>
Type 'ComponentWithAs<"textarea", TextareaProps>' is not assignable to type 'ComponentWithAs<"input", InputProps>'.
Types of property 'propTypes' are incompatible.
Type 'WeakValidationMap<Pick<TextareaProps, "form" | "p" | "slot" | "style" | "title" | "filter" | "children" | "autoComplete" | "name" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | ... 505 more ... | "isReadOnly"> & { ...; } & Pick<...>> | undefined' is not assignable to type 'WeakValidationMap<Pick<InputProps, "form" | "p" | "slot" | "style" | "title" | "filter" | "pattern" | "children" | "autoComplete" | "name" | "defaultChecked" | "defaultValue" | ... 519 more ... | "isReadOnly"> & { ...; } & Pick<...>> | undefined'.
Type 'WeakValidationMap<Pick<TextareaProps, "form" | "p" | "slot" | "style" | "title" | "filter" | "children" | "autoComplete" | "name" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | ... 505 more ... | "isReadOnly"> & { ...; } & Pick<...>>' is not assignable to type 'WeakValidationMap<Pick<InputProps, "form" | "p" | "slot" | "style" | "title" | "filter" | "pattern" | "children" | "autoComplete" | "name" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | ... 518 more ... | "isReadOnly"> & { ...; } & Pick<...>>'.
Types of property 'onCopy' are incompatible.
Type 'Validator<((event: ClipboardEvent<HTMLTextAreaElement>) => void) | null | undefined> | undefined' is not assignable to type 'Validator<((event: ClipboardEvent<HTMLInputElement>) => void) | null | undefined> | undefined'.
Type 'Validator<((event: ClipboardEvent<HTMLTextAreaElement>) => void) | null | undefined>' is not assignable to type 'Validator<((event: ClipboardEvent<HTMLInputElement>) => void) | null | undefined>'.
Type '((event: ClipboardEvent<HTMLTextAreaElement>) => void) | null | undefined' is not assignable to type '((event: ClipboardEvent<HTMLInputElement>) => void) | null | undefined'.
Type '(event: ClipboardEvent<HTMLTextAreaElement>) => void' is not assignable to type '(event: ClipboardEvent<HTMLInputElement>) => void'.
Types of parameters 'event' and 'event' are incompatible.
Type 'ClipboardEvent<HTMLInputElement>' is not assignable to type 'ClipboardEvent<HTMLTextAreaElement>'.
Type 'HTMLInputElement' is missing the following properties from type 'HTMLTextAreaElement': cols, rows, textLength, wrap
I've tried changing it to this
let InputOrTextArea = textarea ? Textarea: Input;
Which now gives me this error
let InputOrTextArea: ComponentWithAs<"input", InputProps> | ComponentWithAs<"textarea", TextareaProps>
JSX element type 'InputOrTextArea' does not have any construct or call signatures.
My guess is that chackra-ui has made some changes since he recorded the tut, so I am not really sure if I create a new Component for TextArea or try digging deeper into this issue.
If one user is logged In, then he/she log out then log In with other account, at first look feeds will be shown as the feeds of previous logged In user so user need to refresh or load more feeds.
Solution is invalidating feeds in cache on login and logout also.
Hi @benawad , I am not sure if this is the right place to ask you this, but I got a bug and it is tricky to kill it.
I am on the 36th minute of the tutorial, I am trying to run the app, do the first migration, and insert the first post.
For some reason, it tries to execute select statement two times and just looks like a lot of funny business with the SQL.
Any ideas, thoughts?
Running into this issue where the server will crash when setting req.session.userId = user.id
:
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Array
I've already set my types.ts
file to include the workaround for the versions of express-session ^1.17.4
:
import { EntityManager, IDatabaseDriver, Connection } from "@mikro-orm/core";
import { Request, Response } from "express";
import { Session, SessionData } from "express-session";
export type MyContext = {
em: EntityManager<any> & EntityManager<IDatabaseDriver<Connection>>;
res: Response;
req: Request & {
session: Session & Partial<SessionData> & { userId?: number };
};
// redis: Redis;
};
How would one go about setting the data in the request session data?
internal/process/promises.js:213
triggerUncaughtException(err, true /* fromPromise */);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Array
at new NodeError (internal/errors.js:322:7)
at Socket.Writable.write (internal/streams/writable.js:285:13)
at RedisSocket.writeCommand (/Users/oleg/Programming/tutorials/lireddit-follow/server/node_modules/@node-redis/client/dist/lib/client/socket.js:57:130)
at Commander._RedisClient_tick (/Users/oleg/Programming/tutorials/lireddit-follow/server/node_modules/@node-redis/client/dist/lib/client/index.js:421:64)
at Commander._RedisClient_sendCommand (/Users/oleg/Programming/tutorials/lireddit-follow/server/node_modules/@node-redis/client/dist/lib/client/index.js:402:82)
at Commander.commandsExecutor (/Users/oleg/Programming/tutorials/lireddit-follow/server/node_modules/@node-redis/client/dist/lib/client/index.js:160:154)
at Commander.BaseClass.<computed> [as set] (/Users/oleg/Programming/tutorials/lireddit-follow/server/node_modules/@node-redis/client/dist/lib/commander.js:8:29)
at RedisStore.set (/Users/oleg/Programming/tutorials/lireddit-follow/server/node_modules/connect-redis/lib/connect-redis.js:65:21)
at Session.save (/Users/oleg/Programming/tutorials/lireddit-follow/server/node_modules/express-session/session/session.js:72:25)
at Session.save (/Users/oleg/Programming/tutorials/lireddit-follow/server/node_modules/express-session/index.js:406:15)
at ServerResponse.end (/Users/oleg/Programming/tutorials/lireddit-follow/server/node_modules/express-session/index.js:335:21)
at ServerResponse.send (/Users/oleg/Programming/tutorials/lireddit-follow/server/node_modules/express/lib/response.js:221:10)
at /Users/oleg/Programming/tutorials/lireddit-follow/server/node_modules/apollo-server-express/dist/ApolloServer.js:89:25 {
code: 'ERR_INVALID_ARG_TYPE'
}
After putting const apolloServer = new ApolloServer({
schema: await buildSchema({
resolvers: [HelloResolver],
validate: false
})
})
Error:
const reflectedType = Reflect.getMetadata(metadataKey, prototype,
propertyKey);
^
TypeError: Reflect.getMetadata is not a function
When running the login test with ApolloGraphQL; the request works fine. However, the cookie is not being set because the browser is blocking the cookie from being set due to SameSite=Lax.
Can anyone offer any guidance on how to get the cookie to be set. I have configured cors to work with the apollographql query studio:
app.use(
cors({
origin: ["http://localhost:3000", "https://studio.apollographql.com"],
credentials: true,
})
);
Here is my session configuration:
app.use(
session ({
name: "qid",
store: new RedisStore({client: redisClient, disableTouch: true}),
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 365 * 10, // 10 years
httpOnly: true,
secure: __prod__, //cookie only works in https
sameSite: "lax", // csrf
},
secret: "keyboard cat",
resave: false,
saveUninitialized: false,
})
);
Any help is greatly appreciated.
The res.clearCookie
function does not clear the cookie in the browser when on the server in production.
This is because the domain
has not been set when clearing the cookie, like it is when you set the session while __prod__
is true
Passing options into res.clearCookie
will fix this however.
res.clearCookie(COOKIE_NAME, {
domain: __prod__ ? '.codeponder.com' : '',
path: '/',
});
You can replace .codeponder.com
with your domain
Hi @benawad ! Thank you for your great videos.
Today I faced with one problem here
Line 7 in 2801126
express-session
even though you tried to import it from express
and it didn't work.Express.Session
I get the error
Namespace 'global.Express' has no exported member 'Session'
i tried to solve it via, but I am not good at typescript ;)
import { Connection, EntityManager, IDatabaseDriver } from "@mikro-orm/core";
import { Request, Response } from "express";
export type MyContext = {
em: EntityManager<IDatabaseDriver<Connection>>;
req: Request & { session: Request };
res: Response;
};
in server/src/types.ts
and
req.session.sessionID = user.id.toString();
in the server/src/resolvers/user.ts
versions:
{
"express": "^4.17.1",
"express-session": "^1.17.1",
}
sorry in advance if I just didn't understand or miss something .
tsnd --respawn --transpile-only index.ts
(ts-node-dev) is usually faster than using tsc
with nodemon
.
The Me query
const [{data, fetching,}] = useMeQuery()
is called twice when the page. I tried removing the<React.StrictMode> but it still gets called twice.
it loads once with no data and then a second time with data and it makes a user component that I made blink. is there a way to wait for it to load and then check for the data or to check for the data before rendering the page? New to this thank you
Hey, I'm kinda stuck at 5:09:03 and im getting the following error:
Argument of type 'FunctionComponent<{ token: string; }> & { getInitialProps?(context: NextPageContext): { token: string; } | Promise<{ token: string; }>; }' is not assignable to parameter of type 'NextComponentType<PartialNextContext, {}, {}>'.
Type 'FunctionComponent<{ token: string; }> & { getInitialProps?(context: NextPageContext): { token: string; } | Promise<{ token: string; }>; }' is not assignable to type 'FunctionComponent & { getInitialProps?(context: PartialNextContext): {} | Promise<{}>; }'.
Type 'FunctionComponent<{ token: string; }> & { getInitialProps?(context: NextPageContext): { token: string; } | Promise<{ token: string; }>; }' is not assignable to type 'FunctionComponent'.
Types of parameters 'props' and 'props' are incompatible.
Type 'PropsWithChildren' is not assignable to type 'PropsWithChildren<{ token: string; }>'.
Property 'token' is missing in type 'PropsWithChildren' but required in type '{ token: string; }'.
With this piece of code:
import { Box, Button, Text } from '@chakra-ui/react';
import { Formik, Form } from 'formik';
import { NextPage } from 'next';
import { withUrqlClient } from 'next-urql';
import Image from 'next/image';
import { useRouter } from 'next/router';
import React from 'react';
import { useState } from 'react';
import { InputField } from '../../components/InputField';
import { Wrapper } from '../../components/Wrapper';
import { useChangePasswordMutation } from '../../generated/graphql';
import { createUrqlClient } from '../../utils/createUrqlClient';
import { toErrorMap } from '../../utils/toErrorMap';
const ChangePassword: NextPage<{ token: string }> = ({ token }) => {
const router = useRouter();
const [, changePassword] = useChangePasswordMutation();
const [tokenErr, setTokenErr] = useState('');
return (
<Wrapper variant='small'>
{/* you know that stuff */}
</Wrapper>
);
};
ChangePassword.getInitialProps = ({ query }) => {
return {
token: query.token as string,
};
};
export default withUrqlClient(createUrqlClient)(ChangePassword);
And I really can't go further, it made so frustrated I'm out of ideas how to fix this. I know, Ben's switching to Apollo Client, but I want to follow the whole tutorial.
Thanks in advance
Thank you so much for this course @benawad, I am almost into 8 hours in it and i started with MongoDB and it worked well until Query Builder started :) so switch to Postgres
Found that we can still query using queryBuilder
const qb = getConnection()
.getRepository(Post)
.createQueryBuilder("p")
.innerJoinAndSelect(
"p.creator",
"user",
"user.id = p.\"creatorId\""
)
.orderBy("p.\"createdAt\"", "DESC");
if (cursor) {
qb.where('p.\"createdAt\" < :cursor', { cursor: new Date(+cursor) })
}
qb.limit(realLimit); // instead of take()
also the query looks much more cleaner than using "take"
SELECT "p"."id" AS "p_id", "p"."uuid" AS "p_uuid", "p"."createdAt" AS "p_createdAt", "p"."updatedAt" AS "p_updatedAt", "p"."title" AS "p_title", "p"."text" AS "p_text", "p"."points" AS "p_points", "p"."creatorId" AS "p_creatorId", "user"."id" AS "user_id", "user"."createdAt" AS "user_createdAt", "user"."updatedAt" AS "user_updatedAt", "user"."username" AS "user_username", "user"."password" AS "user_password", "user"."email" AS "user_email" FROM "post" "p" INNER JOIN "user" "user" ON "user"."id"="p"."creatorId" AND ("user"."id" = p."creatorId") WHERE p."createdAt" < $1 ORDER BY p."createdAt" DESC LIMIT 50
Found this here
Deprecation notice of resolveFieldByKey
- urql-graphql/urql#1219
cache.resolveFieldByKey
is used in two places in cursorPagination
C:\Users\dell\Desktop\project\dist\mikro-orm.config.js:11
dbName = 'lireddit',
^^^^^^^^^^^^^^^^^^^
SyntaxError: Invalid shorthand property initializer at wrapSafe (internal/modules/cjs/loader.js:992:16)
at Module._compile (internal/modules/cjs/loader.js:1040:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:941:32)
at Function.Module._load (internal/modules/cjs/loader.js:782:14)
at Module.require (internal/modules/cjs/loader.js:965:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object. (C:\Users\dell\Desktop\project\dist\index.js:8:44)
at Module._compile (internal/modules/cjs/loader.js:1076:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
[nodemon] app crashed - waiting for file changes before starting...
I got this error when doing the updoot join table
ERROR: more than one row returned by a subquery used as an expression
This was caused because this subquery was returning more than a single row
select value from updoot where "userId" = ${userId} and "postId" = p.id) "voteStatus
Solved by clearing out my updoots table with Updoot.delete({})
before the migrations
I am currently implementing sessions with Redis. I have followed along and have spent sometime debugging on my own, but I can't seem to solve this error.
I am able to send a request, a cookie is set but the server promptly crashes after that with this promise rejection. Any ideas as to what may be going wrong?
Repository: https://github.com/Alphacode18/Lireddit
[discovery] ORM entity discovery started, using ReflectMetadataProvider
[discovery] - processing entity Post
[discovery] - processing entity User
[discovery] - entity discovery finished, found 2 entities, took 23 ms
[info] MikroORM successfully connected to database lireddit on postgresql://[email protected]:5432
[query] select table_name, nullif(table_schema, 'public') as schema_name from information_schema.tables where table_schema not like 'pg_%' and table_schema != 'information_schema' and table_name != 'geometry_columns' and table_name != 'spatial_ref_sys' and table_type != 'VIEW' order by table_name [took 19 ms]
[query] begin
[query] select * from "mikro_orm_migrations" order by "id" asc [took 26 ms]
[query] commit
The server is listening at port 4000
[query] begin
[query] insert into "user" ("created_at", "password", "updated_at", "username") values ('2021-12-25T04:59:34.507Z', '$argon2i$v=19$m=4096,t=3,p=1$ViITDRSY8RBzNYEcZMMZ8A$ZrXebolYIvlbyDx3WFzop/xwPDll4dx/ASz4oKnCL88', '2021-12-25T04:59:34.507Z', 'sham') returning "id" [took 30 ms]
[query] commit
/Volumes/G-DRIVE mobile SSD R-Series/Development/lireddit/node_modules/@node-redis/client/dist/lib/client/index.js:393
return Promise.reject(new errors_1.ClientClosedError());
^
ClientClosedError: The client is closed
at Commander._RedisClient_sendCommand (/Volumes/G-DRIVE mobile SSD R-Series/Development/lireddit/node_modules/@node-redis/client/dist/lib/client/index.js:393:31)
at Commander.commandsExecutor (/Volumes/G-DRIVE mobile SSD R-Series/Development/lireddit/node_modules/@node-redis/client/dist/lib/client/index.js:160:154)
at Commander.BaseClass.<computed> [as set] (/Volumes/G-DRIVE mobile SSD R-Series/Development/lireddit/node_modules/@node-redis/client/dist/lib/commander.js:8:29)
at RedisStore.set (/Volumes/G-DRIVE mobile SSD R-Series/Development/lireddit/node_modules/connect-redis/lib/connect-redis.js:65:21)
at Session.save (/Volumes/G-DRIVE mobile SSD R-Series/Development/lireddit/node_modules/express-session/session/session.js:72:25)
at Session.save (/Volumes/G-DRIVE mobile SSD R-Series/Development/lireddit/node_modules/express-session/index.js:406:15)
at ServerResponse.end (/Volumes/G-DRIVE mobile SSD R-Series/Development/lireddit/node_modules/express-session/index.js:335:21)
at ServerResponse.send (/Volumes/G-DRIVE mobile SSD R-Series/Development/lireddit/node_modules/express/lib/response.js:221:10)
at /Volumes/G-DRIVE mobile SSD R-Series/Development/lireddit/node_modules/apollo-server-express/dist/ApolloServer.js:89:25
at processTicksAndRejections (node:internal/process/task_queues:94:5)
[nodemon] app crashed - waiting for file changes before starting...
Hello Ben,
What about tests for the backend services?
Thanks,
regards
Gianluca
At 9:17, this code:
const [{ data, fetching }] = usePostsQuery({
variables,
});
is causing an error:
TypeError: (0 , generated_graphql__WEBPACK_IMPORTED_MODULE_4_.usePostsQuery) is not a function or its return value is not iterable
The difference between Ben's updoot branch is that his generated/graphql has got an export as:
export function usePostsQuery(options: Omit<Urql.UseQueryArgs<PostsQueryVariables>, 'query'> = {}) {
return Urql.useQuery<PostsQuery>({ query: PostsDocument, ...options });
};
Mine does not. I did run the generator successfully and my generated/graphql does include a Query for posts. It does not however have the above export function.
How do I look for the source of this problem? I'm trying to learn as much as I'm trying to solve this particular problem. Any advice for how to approach problem solving would be gratefully received. I thought the generated/graphql file was created by running yarn gen.
Thank you
there is a deprecation of using createConnection using typeorm , instead you should be doing it like this :
const AppDataSource = new DataSource({
type: "postgres",
host: "localhost",
port: 5432,
username: "test",
password: "test",
database: "test",
synchronize: true,
logging: true,
entities: [Post, Category],
subscribers: [],
migrations: [],
})
AppDataSource.initialize()
.then(() => {
// here you can start to work with your database
})
.catch((error) => console.log(error))
Reference : https://typeorm.io/multiple-data-sources
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.