How to create nextjs getStaticPaths function using dynamic and nested paths (graphql)?
I don't know how I can create the function correctly... Can someone help me? I am using Wordpress headless with graphQL
export async function getStaticPaths() {
const GET_ALL_SLUGS = gql`
query getAllSlugs {
posts {
nodes {
slug
}
}
pages {
nodes {
slug
}
}
}
`;
const response = await client.query({
query: GET_ALL_SLUGS,
});
const categories = response?.data?.pages?.nodes;
const posts = response?.data?.posts?.nodes;
let paths = {
params: {
category: "",
post: "",
},
};
paths = categories.map(({ slug }) => {
return {
params: {
category: slug,
},
};
});
paths = posts.map(({ slug }) => {
return {
params: {
post: slug,
},
};
});
return {
paths,
fallback: false,
};
}
Related
I am trying to fetch data from my mongoDB with NextJS getServerSideProps. Adding data is working but when I use find it does not work.
Here is my model
import { Schema, model, models } from "mongoose";
const testSchema = new Schema({
name: String,
email: {
type: String,
required: true,
unique: true,
}
});
const Test = models.Test || model('Test', testSchema);
console.log(models);
export default Test;
This works so my connection is okay
const createTest = async (event) => {
event.preventDefault();
const name = event.target.name.value;
const email = event.target.email.value;
const res = await fetch('/api/test/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
email,
}),
});
const data = await res.json();
console.log('data: ', data);
};
But this does not work. It shows the 404 page even though there is data
export const getServerSideProps = async () => {
try {
await connectDB();
const tests = await Test.find();
console.log('FETCHED DOCUMENT');
return {
props: {
tests: JSON.parse(json.stringify(tests)),
}
}
} catch (error) {
console.log(JSON.stringify(error,null,2));
return {
notFound: true
}
}
}
Thank you in advance!
This is my server file.
In context I am not getting the request while my test is getting pass while test the required scenario.
export async function buildTestServer({
user,
headers,
roles,
}: {
user?: User;
headers?: { [key: string]: string };
roles?: Role;
}) {
const schema = await tq.buildSchema({
authChecker: AuthChecker,
validate: false,
resolvers: allResolvers(),
scalarsMap: [{ type: GraphQLScalarType, scalar: DateTimeResolver }],
});
const server = new ApolloServer({
schema,
context: async ({ req }) => {
const authHeader = headers?.authorization;
if (authHeader) {
const token = extractTokenFromAuthenticationHeader(authHeader);
try {
const user = await new UserPermissionsService(token).call();
return { req, user };
} catch {
return { req };
}
} else {
if (user) {
let capabilities: any = [];
if (roles) {
capabilities = roles.capabilities;
}
return {
req,
user: {
id: user.id,
customerId: user.customerId,
capabilities,
},
};
} else {
return { req };
}
}
},
});
return server;
}
And this is my test file from where I am sending the request to the server.
My test is getting passed but I am not getting the request headers. I want to check the the request. Can anybody help me out ?
const GET_LIST = `
query GetList($listId: String!) {
GetList(listId: $listId) {
id
}
}
`;
test('Get Lists', async () => {
const customer = await CustomerFactory.create();
const user = await UserFactory.create({ customerId: customer.id });
const list = await ListFactory.create({
customerId: customer.id,
});
const server = await buildTestServer({ user });
const result = await server.executeOperation({
query: GET_LIST,
variables: {
listId: list.id
},
});
var length = Object.keys(result.data?.GetList).length;
expect(length).toBeGreaterThan(0);
});
Just want to update my database after every time pushed the More or Less button (Please take a look at my project ) but the problem is doesn't send the first request and after second request data will send to the firebase and update the special part
react and redux don't have any problem (the base of this project wrote with them) as I asked about it of a redux consultant .
whole the problem come back to involving my app with firebase
Demo :https://zealous-allen-932726.netlify.app/ .
Github : https://github.com/alibidjandy/burger
this is the Api configuration :
import { current } from "#reduxjs/toolkit";
import { createApi, fetchBaseQuery } from
"#reduxjs/toolkit/query/react";
import {
BurgerType,
OrderType,
} from "../components/Layouts/burger/burgerSlice/burgerSlice";
export const burgerApi = createApi({
reducerPath: "burgerApi",
tagTypes: ["Ingredients"],
baseQuery: fetchBaseQuery({
baseUrl:
"https://burger-order-brown-default-rtdb.europe-west1.firebasedatabase.app",
}),
endpoints: (builder) => ({
getIngredients: builder.query<BurgerType, undefined>({
query: () => {
return { url: "/burger.json", method: "GET" };
},
providesTags: ["Ingredients"],
}),
editIngredients: builder.mutation({
query: ({ burger, ing, value, resetToZero }) => {
return {
url: `/.json`,
method: "PATCH",
body: { burger },
};
},
async onQueryStarted(
{ ing, value, resetToZero },
{ dispatch, queryFulfilled }
) {
const patchResult = dispatch(
burgerApi.util.updateQueryData(
"getIngredients",
undefined,
(draft) => {
if (resetToZero) {
const ingredients = draft.ingredients;
ingredients.map((ing) => {
if (ing.Qty) {
ing.Qty = 0;
}
return ing;
});
draft.totalCost = 0;
} else {
const ingredient = draft.ingredients[ing.id]!;
draft.totalCost -= ingredient.Qty! * ingredient.cost!;
ingredient.Qty! += value;
draft.totalCost += ingredient.Qty! * ingredient.cost!;
draft.totalCost.toFixed(2);
if (draft.totalCost < 0) {
draft.totalCost = 0;
}
}
}
)
);
try {
await queryFulfilled;
} catch {
patchResult.undo();
}
},
}),
setOrders: builder.mutation({
query: ({ name, email, postalCode, street, burger }) => {
return {
url: "/orders/.json",
method: "POST",
body: { name, email, postalCode, street, burger },
};
},
}),
getOrders: builder.query<OrderType[], undefined>({
query: () => {
return { url: "/orders.json", method: "GET" };
},
providesTags: ["Ingredients"],
}),
}),
});
export const { editIngredients, getIngredients } = burgerApi.endpoints;
export const {
useGetIngredientsQuery,
useEditIngredientsMutation,
useGetOrdersQuery,
useSetOrdersMutation,
} = burgerApi;
current url is: http://localhost:3000/products/60e03e16229da058968f33c3
but i want to mask it as http://localhost:3000/products/product-1
This is the getStaticPaths code that i have (uses apollo client to fetch the data)
const GET_ALL_QUERY = gql`
{
products {
id
}
}
`;
export async function getStaticPaths() {
const paths = await client
.query({
query: GET_ALL_QUERY,
})
.then((data) => {
const productsData = data.data.products;
if (productsData.length) {
return productsData.map((res) => {
return { params: { id: res.id } };
});
}
})
.catch((err) => Promise.reject(new Error(err)));
return {
paths,
fallback: false,
};
}
export async function getStaticProps({ params }) {
try {
const res = await client.query({
query: GET_ONE_QUERY,
variables: { id: params.id },
});
return {
props: res.data.product,
};
} catch (err) {
throw new Error(err);
}
}
if i use
<Link href={`/products/${product_id}` as={`/products/${product_name}`}>
</Link>
it doesnt seem to work. it is looking for /product-1 page and returns page not found.
also in sever.js,
i have
const server = express();
server.get("/products/:id", (req, res) => {
const actualPage = "/products";
const queryParams = { id: req.params.id };
console.dir("req.params.id = " + JSON.stringify(req.params.id));
app.render(req, res, actualPage, queryParams);
});
suspecting if this could be affecting the dynamic path.
I am not able to figure out the solution. Searched extensively but all resources refer to using only the id. Is this possible in nextjs ?
I'm extremely new when it comes to using VueJS and so I am working on a small App that should list out an Authenticated person's Github repositories.
I'm having trouble when it comes to being able to access or even traverse the Array in the Picture below. I keep getting an error of undefinedif I try userRepos. Please see my code below.
I do apologize for the "Wall of Code". But I thought these javascript code snippets are the most pertinent to the issue.
This is the GitHub repo I am using as the boilerplate for this project. GitHub-Electron-Vue-OAuth
const getAxiosClient = (state) => {
return axios.create({
baseURL: state.server.url, // this is "https://api.github.com
headers: {
'Authorization': 'token ' + state.session.access_token
},
responseType: 'json'
})
}
// Mutation
[types.SET_USER_REPOS](state, repos) {
state.session.repos = repos;
},
// State Object
const state = {
server: {
url: 'http://api.github.com'
},
session: {
access_token: window.localStorage.getItem('access_token'),
ready: false,
authenticated: false,
user: {}
}
};
// Actions
export const getRepos = ({
commit,
state
}) => {
return new Promise((resolve, reject) => {
getAxiosClient(state).get('/user/repos').then(response => {
commit(types.SET_USER_REPOS, response.data)
resolve(response.data)
}, err => {
console.log(err)
reject(err)
})
})
}
export const userRepos = (state) => {
console.log(state.session.repos)
return state.session.repos;
}
<template lang="jade">
.home
span Hello {{ username }}
span {{ userRepos }}
</template>
<script>
export default {
name: 'home',
computed: {
username() {
return this.$store.getters.username;
},
userRepos() {
return this.$store.getters.userRepos;
}
},
// TODO: Push this in router
beforeRouteEnter(to, from, next) {
next(vm => {
if (!vm.$store.getters.isAuthenticated) {
vm.$router.push({
name: 'login'
});
} else {
next();
}
});
}
}
</script>