Best way to learn is through experience oritented questions and answers
How to create sitemap in Next JS when using app router?
Create a sitemap.ts
file in app directory
Sample code for blogs:
import { BASE_URL } from "@/lib/constants"; import { getSortedPostsData } from "@/lib/posts"; import { generateBlogDetailPath } from "@/lib/urlHelper"; import { MetadataRoute } from "next"; export default async function sitemap(): MetadataRoute.Sitemap { const posts = getSortedPostsData(); return posts.map((post) => ({ url: `${BASE_URL}${generateBlogDetailPath(post.slug)}`, lastModified: post.date, })); }
https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap https://nextjs.org/docs/app/api-reference/functions/generate-sitemaps
Where to add a robots.txt in Next JS 14?
In public folder. Reference: https://nextjs.org/docs/app/api-reference/file-conventions/metadata/robots
How to generate metadata in NextJS 14?
Where and how to add icons like favico?
You can add favico, icon or apple-icon in app directory and it will be added to the html head automatically. https://nextjs.org/docs/app/api-reference/file-conventions/metadata/app-icons
How to add a todo list in markdown file?
Make sure you have a list with -
and then create brackets with space
for unchecked and brackets with x
for checked
- [ ]
- [x]
How to add a custom meta tag in a static way?
For it to be on the home page, from root layout file, do this:
export const metadata: Metadata = { other: { "google-site-verification": "ds-l9Fc", }, };
it is to be added inside the other key
How to verify your website on google search console?
There are many methods, we can add a google verification meta tag on the home page.
How to disable automatic dark mode in tailwind?
Add this in tailwind.config.ts
const config: Config = { darkMode: "class" }
How to render a responsive image in NextJS 13 which generates blur url automatically?
For nextjs to generate blur url automatically, image should be statically imported like this. This way nextjs can automatically figure out the width and height of the image and can also automatically generate a blur image if you provide placeholder=blur
value, default value = empty
import myImage from './myImage.png;
<Image priority src={myPic} alt="Gaurav Sobti pic" className="object-contain w-[40%] h-[auto]" placeholder="blur" />
Prism from react-syntax-highlighter has a large footprint of around 420kb, how can you reduce it?
Use PrismLight and register the languages you want to highlight.
import { PrismLight as SyntaxHighlighter } from "react-syntax-highlighter"; import tsx from "react-syntax-highlighter/dist/esm/languages/prism/tsx"; import jsx from "react-syntax-highlighter/dist/esm/languages/prism/jsx"; SyntaxHighlighter.registerLanguage("jsx", jsx); SyntaxHighlighter.registerLanguage("tsx", tsx);
How to tell typescript compiler that the value won't be null or undefined when it's not able to infer itself?
Just use non-null assertion operator: !
// Compiled with --strictNullChecks function validateEntity(e?: Entity) { // Throw exception if e is null or invalid entity } function processEntity(e?: Entity) { validateEntity(e); let s = e!.name; // Assert that e is non-null and access name }
What's the use case of ts-node-dev package?
Allows to execute Typescript code with live-reload on file
In VSCode, in a NextJs project, eslint is working but it is still not showing Typescript errors, why?
Press ctrl + shift + p
and then open user settings
. Make sure that typescript.validate.enable
is enabled.
What does the command npx prisma init
do?
schema.prisma
file inside prisma folder which contains the start of a Prisma schema.How to model a one-to-many relation between two models in prisma?
Let's take an example of User with id field and messages models.
model User { id Int @id @default(autoincrement()) messages Message[] } model Message { id Int @id @default(autoincrement()) userId Int user User @relation(fields: [userId], references: [id]) }
What's the right way to think about your prisma schema?
Think of the Prisma Schema as the glue between the shape of your database and the API that interacts with it.
How to perform a prisma db migration?
npx prisma migrate dev
And if you want to name the migration:
npx prisma migrate dev --name init
Give an example of seed file for prisma
// seed.ts import { PrismaClient } from "@prisma/client"; const prisma = new PrismaClient(); async function main() { // Delete all `User` and `Message` records await prisma.message.deleteMany({}); await prisma.user.deleteMany({}); // (Re-)Create dummy `User` and `Message` records seedData.forEach(async (user) => { await prisma.user.create({ data: user }); }); } main().then(() => { console.log("Data seeded"); });
How to run a prisma seed file?
seed file is a normal js or ts file. So we can run it with node or typescript or ts-node-dev like this
ts-node-dev prisma/seed.ts
What are the 2 approaches to building a GraphQL schema?
What scalar data types does graphql support by default?
How to define a custom scalar type in graphql like Date?
There are pre-made custom scalar type definitions available in the open source community: graphql-scalars They can be used like this:
import SchemaBuilder from "@pothos/core"; import { DateResolver } from "graphql-scalars"; export const builder = new SchemaBuilder<{ Scalars: { Date: { Input: Date; Output: Date }; }; }>({}); builder.addScalarType("Date", DateResolver);
How can you be sure that your frontend graphql query will stay in sync with the backend schema?
By using Graphql Codegen
What are the roles of Prisma, Pothos and Graphql codegen in a typescript node js and react full-stack project?
What accurately describes a graph in GraphQL?
In simplest terms what is a schema in Graphql?
It's a collection of object types
that contain fields
.
What is the best practice for name of a type in graphql?
PascalCase
type SpaceCat { # Fields go here }
Give an example of graphql type using SDL(Schema Definition Language)
How to write description for a schema?
"I'm a regular description" type SpaceCat { } """ I'm a block description with a line break """ type SpaceCat { "I am description of the field" name: String! }
What is the use of graphql-tag
package?
It provides tag template literal, used for wrapping Graphql strings like schema definition. It converts GraphQL string into the format Apollo libraries expect. It also enables syntax highlighting.
What's the naming convention for query names?
ALL_CAPS
const TRACKS = gql` #Query goes here `;
Is Mutation a type?
Yes Mutation
is a type like Query
, it serves as an entry to our schema.
type Mutation { addSpaceCat(name: String!): SpaceCat }
What is a good way to name mutations?
Start with a verb that describes the specific action of our update operation: add, delete or create
followed by whatever data the mutation acts on. Eg:
deleteMission
createMission
When a mutation updates more than one object, which one should we return? In addition what common fields should be added to a mutation response?
We should return all the updated objects because our client might need to use them to update the UI and then doesn't need to query another API. These should be the additional commond fields in a mutation response:
code
: an Int that refers to the status of the response, similar to an HTTP status code.
success
: a Boolean flag that indicates whether all the updates the mutation was responsible for succeeded.
message
: a String to display information about the result of the mutation on the client side. This is particularly useful if the mutation was only partially successful and a generic error message can't tell the whole story.
Create a separate mutation response type in multiple response case.
When returning a response for mutation, why should the type of the data being returned should be nullable?
Because there might be an error in mutating the data and hence we need to return null.
When calling a *DataSource
in Apollo graphql, how to catch errors?
incrementTrackViews: async (_, {id}, {dataSources}) => { try { const track = await dataSources.trackAPI.incrementTrackViews(id); return { code: 200, success: true, message: `Successfully incremented number of views for track ${id}`, track }; } catch (err) { return { code: err.extensions.response.status, success: false, message: err.extensions.response.body, track: null }; } },
Which hook do we need to use for calling mutation from client react side?
useMutation
What does calling useMutation
return?
It returns an array with 2 elements. First is the function which will actually be used to call the mutation , second contains the state of the mutation call: loading, error and data
const [incrementTrackViews, { loading, error, data }] = useMutation( INCREMENT_TRACK_VIEWS, { variables: { incrementTrackViewsId: id }, } );
On the client side (React) when do we need to regenerate types in graphql?
When we add a new operation like a query or mutation. For example when we add a new mutation to update the authentication state.
Which data structure does graphql use to check if a query is valid?
Abstract Syntax Tree
Is the resolver function executed for every field in a query?
Yes
Which of these are responsibilities of a resolver function?
[x] Retrieving the correct data from a source such as a database or a REST API [x] Populating its corresponding field with data [x] Constructing an AST from each incoming GraphQL query string
What questions to ask ourselves before designing graphql schema?
What if the API from where you will resolve data using graphql contains bunch of extra stuff that you don't need?
The resolver function can filter out the properties that are required
Can a graphql API connect to multiple data sources?
Yes
What is a N + 1 problem in API call?
When we make 1 call to fetch top level data and subsequent N calls to retrieve child data which is same in every call.
What is RESTDataSource?
It is a substitue for fetch in graphql. It helps in caching and deduplication of REST API calls out of the box.
When to use encodeURIComponent?
To prevent malicious clients from accessing or manipulating data they shouldn't be, we recommend using the encodeURIComponent function for any HTTP path that accepts dynamic input.
getAuthor(authorId) { return this.get(`author/${encodeURIComponent(authorId)}`); }
What should a resolver's name correspond to?
A resolver's name should correspond to its field name.
Explain a resolver's params: parent, args, contextValue, info
parent
is the returned value of the resolver for the field's parent. This will be useful when dealing with resolver chains.
args
contains all GraphQL arguments that were provided for the field by the GraphQL operation.
contextValue
is an object shared across all resolvers that are executing for a particular operation. The resolver needs this argument to share state, like authentication information, a database connection, or a DataSource.
info
contains information about the operation's execution staet, including the field name, the path to the field from the root, and more. It's not used as frequently as the others, but it can be useful for more advanced actions like setting cache policies at the resolver level.You c
How to pass contextValue to your resolver function?
Where we have initialised apollo server and started the standalone apollo server. We can do something like this:
const { url } = await startStandaloneServer(server, { context: async () => { return { dataSources: { trackAPI: new TrackAPI(), }, }; }, });
Within a graphql server response, which keys can you expect to find in the JSON object?
errors
keydata
keyIs it possible to get partial response from a graphql query in case of an error?
Yes
When you query a graphql field that is not in the schema, what error code will the server send?
GRAPHQL_VALIDATION_FAILED
How to setup an apollo client?
import { ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client'; const client = new ApolloClient({ uri: 'http://localhost:4000', cache: new InMemoryCache(), }); ReactDOM.render( <ApolloProvider client={client}> <GlobalStyles /> <Pages /> </ApolloProvider>, document.getElementById('root') );
Given this schema field: missions: [Mission!], what does it mean?
The list's items can't be null
Where can we add entry points to our schema?
In the Query type
Give examples of how to pass arguments
type Query {
"argument is mandatory and of type id and returns a SpaceCat object"
spacecat(id: ID!): SpaceCat
"accepts 2 arguments: to of nullable type String and scheduled of nullable type Boolean"
missions(to: String, scheduled: Boolean): [Mission]
}
What is a resolver chain?
A graphql query in many cases has nested fields. We can associate resolvers for every field. When we write resolvers for nested fields and take advantage of the data inside the parent which was returned through parent resolver, it is called resolver chaining.
query track(id: ‘c_0') { title author { name } }
Here we can write a resolver for author and use the trackId from the parent to get that data.
How to make sure that a query accepts a non-nullable string variable isPresent?
query getData($isPresent: String!){ title }
How to pass a trackId variable from client side using useQuery?
const { loading, error, data } = useQuery( MY_QUERY, { variables: { trackId }});