Cant delete item from sqlite by qraphql mutation - sqlite

I'm learning to write apollo server by following a graphql tutorial https://www.howtographql.com/graphql-js/3-a-simple-mutation/ but when I try to write a delete mutation and use it in the GraphQL Playground, I get null after executing, and if I check data in the Prisma studio there is no change
mutation delete and server response
I'm sure that there are many items for deleting also with current id which I used for delete
this is my code
prisma studio data
const {ApolloServer} = require('apollo-server');
const fs = require('fs');
const path = require('path');
const { PrismaClient } = require('#prisma/client')
const prisma = new PrismaClient()
const resolvers = {
Query : {
info: () => 'Info text',
feed: async (parent, args, context, info) => {
return context.prisma.link.findMany()
},
},
Mutation : {
post: (parent, args, context, info) => {
const newLink = context.prisma.link.create({
data: {
url: args.url,
description: args.description,
},
})
return newLink
},
delete: (parent, args, context, info) => {
const deleteLink = context.prisma.link.delete({
data: {
id: args.id
}
})
return deleteLink
}
}
}
const server = new ApolloServer({
typeDefs: fs.readFileSync(
path.join(__dirname, 'schema.graphql'),
'utf8'
),
resolvers,
context: {
prisma,
}
})
server
.listen()
.then(({url})=>
console.log(`Server is running on ${url}`)
);

I gat it. Instead data use where. Prisma supports filtering with where query option.
async function deleteLink(parent, args, context, info){
const deleteLink = context.prisma.link.delete({
where: {
id: +args.id,
}
})
}

Related

Apollo client can't query in Nextjs getServerSideProps via SchemaLink

Apollo client fails to do query when initialized with SchemaLink (nexus) instead of HttpLink. I get this error Cannot set properties of undefined (setting 'select')
function createIsomorphLink() {
if (typeof window === 'undefined') {
const { SchemaLink } = require('#apollo/client/link/schema')
const { schema } = require('./nexusSchema')
return new SchemaLink({ schema })
} else {
const { HttpLink } = require('#apollo/client/link/http')
return new HttpLink({
uri: '/api/graphql',
credentials: 'same-origin',
})
}
}
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === 'undefined',
link: from([errorLink, createIsomorphLink()]),
cache: new InMemoryCache(),
})
}
Here's my getServerSideProps. I initialize apollo client and use apolloClient.query(...)
export const getServerSideProps = async ({ params }) => {
const id = params.id
const apolloClient = initializeApollo()
// Here's where the error occurs
const { data } = await apolloClient.query({
query: gql`
query findUniquePage($id: String!) {
findUniquePage(where: { id: $id }) {
title
type
content
isPublished
}
}
`,
variables: { id },
})
// ...snippet..
}
I tried creating simple 'hello' query with string response, so that there was no select part. But error stayed the same.
export const getServerSideProps = async () => {
const apolloClient = initializeApollo()
const { data } = await apolloClient.query({
query: gql`query hello { hello }`,
})
return {
props: {},
}
}
My apollo client version is 3.7.0. The latest is 3.7.1 but by CHANGELOG there seems to be nothing that addresses my issue. Probably, the problem is how apollo client requests my api via SchemaLink, or how my api parses that request (apollo server + code first nexus). Because when I replaced SchemaLink with HttpLink, code worked fine. But I kinda want to keep the SchemaLink. Any advice?

Can i create a Nextjs dynamic route [id]-[first_name]-[last_name]?

I am using nextjs to build a directory. I effectively want to click on 'more info' and an info page to load under the URL of /info/[id]-[first_name]-[last_name].
I am pulling data from an api by id, which will then get the first_name and last_name data.
I have a file inside an info folder named [id]-[first_name]-[last_name] :
export default function Info({ info }) {
return (
<div>
<h1>First Name</h1>
<p> Last Name </p>
</div>
);
}
export const getStaticPaths = async () => {
const res = await fetch('http://xxx:1337/api/info');
const data = await res.json();
// map data to an array of path objects with params (id)
const paths = [data].map(info => {
return {
params: [{
id: `${info.id}-`,
first_name: `${info.first_name}-`,
last_name: `${info.last_name}`
}]
}
})
return {
paths,
fallback: false
}
}
export const getStaticProps = async (context) => {
const id = context.params.id;
const res = await fetch('http://xxxx:1337/api/info/' + id);
const data = await res.json();
return {
props: { info: data }
}
With this I just get the error:
Error: A required parameter (id]-[first_name]-[last_name) was not provided as a string in getStaticPaths for /info/[id]-[first_name]-[last_name]
I guess that error is pretty self-explanatory, but I am blocked at this point. I have seen that i may be able to use a slug, but that means re-working a lot of the api.
Any direction with this is apprecated. Thanks!
in this way you can catch all attributes /info/[id]/[first_name]/[last_name]
by making the file /info/[...slug]
export const getStaticProps = async ({ query }) => {
const [id ,firstname ,lastname] = query.slug }
or keep it /info/[slug] and get it as string after that you can split it

How to combine next-i18next into an existing getServerSideProps function in NextJS

I have a Next page that uses next-i18next in a getServerSideProps and I have another page that uses getServerSideProps to pull data from MongoDB. Both work correctly.
I would like to be able to add next-i18next to the function that connects to Mongo (basically combine the getServerSideProps functions), but I'm getting the error:
nexti18n-next Error: Initial locale argument was not passed into serverSideTranslations'
The first page's getServerSideProps function that connects to next-i18n
export const getServerSideProps = withAuthUserSSR({ whenUnauthed: AuthAction.REDIRECT_TO_LOGIN,})(async ({ locale, }) => {
return {
props: {
...(await serverSideTranslations(locale,
[
'language-file',
...
]
)),
},
};
})
The getServerSideProps function in the second page that pulls data from Mongo:
export const getServerSideProps = withAuthUserSSR({ whenUnauthed: AuthAction.REDIRECT_TO_LOGIN })(async (context) => {
const username = context.params.var[0];
const userId = context.params.var[2];
const { db } = await connectToDatabase();
const pipeline = [
...
]
const postdata = await db.collection('posts').aggregate(pipeline).toArray();
return {
props: {
userId,
username,
postdata: JSON.parse(JSON.stringify(postdata)),
},
};
})
Is it possible to 'add' the next-i18next code to the second function? It seems to me to be an issue with the different way 'locale' and 'context' are defined in each function. I have tried lots of combinations of both but end up messing up either the mongo query or the translations.
This is how I thought it would be done:
export const getServerSideProps = withAuthUserSSR({ whenUnauthed: AuthAction.REDIRECT_TO_LOGIN })(async (context,{ locale, }) => {
const username = context.params.var[0];
const userId = context.params.var[2];
const { db } = await connectToDatabase();
const pipeline = [
...
]
const postdata = await db.collection('posts').aggregate(pipeline).toArray();
return {
props: {
...(await serverSideTranslations(locale,
[
'language-files',
...
]
)),
userId,
username,
postdata: JSON.parse(JSON.stringify(postdata)),
},
};
})
Many thanks for any possible help!

next-redux-wrapper Wrapper.getStaticProps not working with

This is my backend controller, I am getting the rooms data
const allRooms = catchAsyncErrors(async (req, res) => {
const resPerPage = 4;
const roomsCount = await Room.countDocuments();
const apiFeatures = new APIFeatures(Room.find(), req.query)
.search()
.filter()
let rooms = await apiFeatures.query;
let filteredRoomsCount = rooms.length;
apiFeatures.pagination(resPerPage)
rooms = await apiFeatures.query;
res.status(200).json({
success: true,
roomsCount,
resPerPage,
filteredRoomsCount,
rooms
})
})
This is my redux actions I am sending the payload and data
export const getRooms = (req, currentPage = 1, location = '', guests, category) => async (dispatch) => {
try {
const { origin } = absoluteUrl(req);
let link = `${origin}/api/rooms?page=${currentPage}&location=${location}`
if (guests) link = link.concat(`&guestCapacity=${guests}`)
if (category) link = link.concat(`&category=${category}`)
const { data } = await axios.get(link)
dispatch({
type: ALL_ROOMS_SUCCESS,
payload: data
})
} catch (error) {
dispatch({
type: ALL_ROOMS_FAIL,
payload: error.response.data.message
})
}
}
This is my reducer function, dispatching the room data
export const allRoomsReducer = (state = { rooms: [] }, action) => {
switch (action.type) {
case ALL_ROOMS_SUCCESS:
return {
rooms: action.payload.rooms
}
case ALL_ROOMS_FAIL:
return {
error: action.payload
}
case CLEAR_ERRORS:
return {
...state,
error: null
}
default:
return state
}
}
Here I want to get the data using wrapper.getStaticProps but I am getting an error, but when i am using wrapper.getServerSideProps I get the data.
export const getStaticProps = wrapper.getStaticProps(store=> async ({ req, query, }) => {
await store.dispatch(getRooms(req, query.page, query.location, query.guests, query.category))
})
It seems that in ({ req, query, }) => , query is undefined.
Going by the documentation of next, the context object for getStaticProps has no property query. It is only available in getServerSideProps.
See also this info:
Only runs at build time
Because getStaticProps runs at build time, it does not receive data that’s only available during request time, such as query parameters or HTTP headers as it generates static HTML.

App working locally but not on production: TypeError: Cannot read property 'titulo_categoria' of undefined

I'm trying to deploy an app using Prismic as CMS and everything works perfectly locally, but once I deploy to vercel I get the error:
19:09:51.850 | TypeError: Cannot read property 'titulo_categoria' of undefined
There seems to be something wrong when it tries to get the data from Prismic.
My code is the following:
import {getAllCategorias, getCategory2} from '../../lib/api';
export default function Index({cat}) {
return <>{cat.titulo_categoria[0].text}</>;
}
export async function getStaticProps({params}) {
const data = await getCategory2(params.slug);
return {
props: {
cat: data?.categorias ?? null,
},
};
}
export async function getStaticPaths() {
const allPosts = await getAllCategorias();
return {
paths: allPosts?.map(({node}) => `/test/${node._meta.uid}`) || [],
fallback: true,
};
}
And the API code that gets data from Prismic is:
import Prismic from 'prismic-javascript';
const REPOSITORY = process.env.PRISMIC_REPOSITORY_NAME;
const REF_API_URL = `https://${REPOSITORY}.prismic.io/api/v2`;
const GRAPHQL_API_URL = `https://${REPOSITORY}.prismic.io/graphql`;
// export const API_URL = 'https://your-repo-name.cdn.prismic.io/api/v2'
export const API_TOKEN = process.env.PRISMIC_API_TOKEN;
export const API_LOCALE = process.env.PRISMIC_REPOSITORY_LOCALE;
export const PrismicClient = Prismic.client(REF_API_URL, {
accessToken: API_TOKEN,
});
async function fetchAPI(query, {previewData, variables} = {}) {
const prismicAPI = await PrismicClient.getApi();
const res = await fetch(
`${GRAPHQL_API_URL}?query=${query}&variables=${JSON.stringify(variables)}`,
{
headers: {
'Prismic-Ref': previewData?.ref || prismicAPI.masterRef.ref,
'Content-Type': 'application/json',
'Accept-Language': API_LOCALE,
Authorization: `Token ${API_TOKEN}`,
},
}
);
if (res.status !== 200) {
console.log(await res.text());
throw new Error('Failed to fetch API');
}
const json = await res.json();
if (json.errors) {
console.error(json.errors);
throw new Error('Failed to fetch API');
}
return json.data;
}
export async function getCategory2(slug) {
const data = await fetchAPI(
`
query CategoryBySlug($slug: String!, $lang: String!) {
categorias(uid: $slug, lang: $lang) {
titulo_categoria
_meta {
uid
}
}
}
`,
{
variables: {
slug,
lang: API_LOCALE,
},
}
);
return data;
}
Any idea what's wrong with this? I been trying to figure it out for the whole day without any luck
Perhaps you already checked that, but since you mentioned everything works locally and not on Vercel are you sure your environment variables are set there? Especially PRISMIC_API_TOKEN since it appears you're relying on it to query the API?
Also I'm a bit worried about that part of the code:
props: {
cat: data?.categorias ?? null,
}
...where you might be sending a null value to your Index component resulting in your error, I'd try that instead:
props: {
cat: data?.categorias ?? {},
}
...plus using the safe navigation operator (?.) on the Index component?
Let me know how it goes!

Resources