Continuing the 100doc challenge, although with a break 😜
Read Part 1 here.
Submit the ‘message sent to a user’ to DB, by username
How to fetch
- promise version
- async await version
https://rapidapi.com/guides/fetch-api-async-await
Dont forget to add req body!
in client:
in /[username].js
function addNoteHandler(noteData) {
//console.log(`in [username], got noteData: ${JSON.stringify(noteData)}`);
//submit to DB API
fetch("/api/add-note", {
method: "POST",
body: JSON.stringify({ test: "test" }),
// Adding headers to the request. It is actually optiona here.
headers: {
"Content-type": "application/json; charset=UTF-8",
},
})
.then((res) => {
return res.json();
})
.then((res) => {
console.log(res);
});
}
at server:
export default async function handler(req, res) {
//due to concatenation, prints [object Object]
console.log("at /api/add-note, req body " + req);
//shows that type is object
console.log("typeof req body " + typeof req);
// below commented line will give error:
/*
* https://stackoverflow.com/questions/27101240/typeerror-converting-circular-structure-to-json-in-nodejs
* happens when strinfigying req.
*/
//console.log("typeof req body " + JSON.stringify(req));
//directly printing req shows it is indeed an object (due to absence of concatenation, it shows its real content, instead of [object Object])
console.log(req);
//access req.body without any problem
console.log(req.body) // prints { test: 'test' }
res.status(200).json({ name: "John Doe" });
}
When connecting to DB, I realized I have DB that looks like this (has this schema currently):
- db:
notes
has collection notes
:
_id:6289dbb9665bacfa9931ad5d,
message:"Message for you"
_id:628c3d0303ce3a46a2e33025
message:"Where are you?"
- db:
users
has collection users
:
_id
:
62904c3e4031695742c58665
username
:
"anant"
name
:
"Anant"
_id
:
62904c7a4031695742c58666
username
:
"anthony"
name
:
"Anthony"
So if I use the (1) notes db and notes collection,
I need to have 1 more key: username
.
- Will searching (‘query’, when I load data) work well? If I store every user’s data in single collection?
To answer this I googled:
how to store user data in mongodb
found this blogpost
and then this official documention, looks useful. Will check this later.
TODO read above, specially the official
For now, updating the notes collection.
adding 1 more key: username
Google: how to insert to a collection mongodb
its done using insertOne(<your object>)
I noticed(because insetOne gave this error: error - TypeError: Cannot create property '_id' on string '{"username":"anant","message":"sfgsdfgasdfasdasasdfdfasdfadasdfsfadsfaasdfasdfdsfasdfasdfasfd"}'
) that I was passing string to it!
means that req
in api route handler is an object.
req.body of the POST request is always a string (JSON string).
So need to parse it.
Wow it actually inserted it!!!
As we can see the data has different schema.
Also fixed the redirect after submit.
Now - implement login and session with next-auth
Next-Auth is used for authentication, from examples seems pretty cool.
Following the getting started
Will develop this feature on a new branch
git checkout -b login-impl
Step 1
Add API route
https://next-auth.js.org/getting-started/example#add-api-route
Configure Shared session state
Modified _app.js
Step 2
Frontend - Add React Hook
https://next-auth.js.org/getting-started/example#frontend---add-react-hook
Now thinking of doing this on Navigation/layout page.
components\layout\MainNavigation.js
Did following change for now:
import classes from "./MainNavigation.module.css";
import Link from "next/link";
import { useSession, signIn, signOut } from "next-auth/react";
function MainNavigation() {
const { data: session } = useSession();
if (session) {
return (
<header className={classes.header}>
<div className={classes.logo}>
<Link href="/">Notes</Link>
</div>
<nav>
<ul>
<li>
<Link href="/">All Notes</Link>
</li>
<li>
<button onClick={() => signOut()}>Sign out</button>
</li>
</ul>
</nav>
</header>
);
}
return (
<header className={classes.header}>
<div className={classes.logo}>
<Link href="/">Notes</Link>
</div>
<nav>
<ul>
<li>
<Link href="/">All Notes</Link>
</li>
<li>
<button onClick={() => signIn()}>Sign in</button>
</li>
</ul>
</nav>
</header>
);
}
export default MainNavigation;
Step 3
Backend - API Route
https://next-auth.js.org/getting-started/example#backend---api-route
create pages/api/restricted.js
Documentation
https://developers.google.com/identity/protocols/oauth2