How to configure apollo server with meteor with the meteor/apollo package? - meteor

I'm trying to build an app with meteor, apollo/graphql for the first time and the tutorial I'm watching might have outdated versions of apollo. I set up my server as:
import { createApolloServer } from "meteor/apollo";
import { makeExecutableSchema } from "graphql-tools";
const typeDefs = `
type Query {
hi: String
}
`;
const resolvers = {
Query: {
hi() {
return "Hello world";
}
}
};
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
createApolloServer({ schema });
However I usually get this as an error:
TypeError: graphqlExpress is not a function
I know it has to do with the apollo package, but I don't know how to get the migration changes made for apollo 2.0.0 into the meteor/apollo file from the migration doc on apollo's site. Any help is appreciated!

Related

Sanity and NextJs -> TypeError: Cannot read properties of undefined (reading 'fetch')

Im trying to create a portfolio site for myself using sanity on the backend. The site is working and the DB is set up and working using Sanity studio, but I cant get it to connect properly on the backend using Next.
Here is my connection file:
import { createClient } from "next-sanity";
import createImageUrlBuilder from "#sanity/image-url";
export const client = createClient({
projectId: "p079sml5",
dataset: "production",
apiVersion: "2023-01-31",
useCdn: false,
});
I'll be hiding a lot of this in env files but for the purposes of debugging I've left the info in.
And here is one of my endpoints:
import { NextApiRequest, NextApiResponse } from "next";
import { groq } from "next-sanity";
import { client } from "sanity";
import { Social } from "./typings";
const query = groq`
*[_type == "social"]
`;
type Data = {
socials: Social[];
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const socials: Social[] = await client.fetch(query);
res.status(200).json({ socials });
}
As per the title, when trying to make the call on http://localhost:3000/api/getSocials, I get the following error: error - TypeError: Cannot read properties of undefined (reading 'fetch')
at handler (webpack-internal:///(api)/./src/pages/api/getSocials.ts:15:70)
Fetch appears on the autofill, along with the other methods, so it would appear that its been imported "correctly". The error suggests that that its the client that is the issue but cant figure out why.
Thanks in advance
Ive tried, using my dev environment, with the associated project id etc but no joy.
UPDATE: Fixed, I just moved the client file into a different folder, and it worked
Follow this doc https://github.com/vercel/next.js/tree/canary/examples/cms-sanity
Or setup this repo in new folder and update it's config (/lib/config.js) file with your sanity details then check... previously it was worked for me.

How to use runtime config in composable?

I want to do this
composables/apiFetch.ts
import { $fetch } from 'ohmyfetch'
export const useApiFetch = $fetch.create({ baseURL: useRuntimeConfig().apiUrl })
And use it within Pinia so I don't repeat myself writing $fetch.create over and over again for every single API call.
somewhere_in_pinia.ts
...TRIM...
actions: {
async doSomething(payload: SomeNicePayload): Promise<void> {
const response = await useApiFetch('/something', { method: 'POST', body: payload })
}
}
...TRIM...
But Nuxt won't allow me
[nuxt] [request error] nuxt instance unavailable
at useNuxtApp (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:472:13)
at Module.useRuntimeConfig (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:480:10)
at $id_Yl353ZXbaH (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:38358:90)
at async __instantiateModule__ (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:40864:3)
I have been looking for solution online, followed instruction from the official discussion to no avail.
EDIT
I don't want to use Nitro, since my backend is already written on Laravel. I need to access the host without re-typing it all over the place so I thought I could use .env and runtimeConfig.
you are trying to access Nuxt instance while it's not ready yet. To make it work, write your composable as a function :
import { $fetch } from 'ohmyfetch'
export const useApiFetch = (url, params) => {
const instance = $fetch.create({ baseURL: useRuntimeConfig().apiUrl })
return instance(url, params)
}

How To Unit Test NextJS API Route That Uses Repository Pattern?

I am new prisma / nextjs user and I am trying to understand how to unit test an API route that uses prisma. I have read the unit testing guide.
I like the dependency injection approach and have started trying to implement it. However I am struggling with the following development issue. Can anybody help?
With the dependency injection approach the unit testing guide explains how to setup the mock context and use this in the data access layer. Does anyone have any examples of how and where the real context could be initialised and used with an API route that uses a repository pattern? Is it possible to expand the next.js api handler with middleware to include the context to facilitate testing?
import type { NextApiRequest, NextApiResponse } from 'next'
import { PublishRepository } from '../../../repository'
// PUT /api/publish/:id
export default async function handle(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method == 'PUT') {
const postId = req.query.id;
let repo = new PublishRepository( // where does the live context come from and how is it initialised??? )
const post = repo.set_published(postId)
res.json(post);
}
}
Repository - Initialised using Context instance - How is this initialise for development and how is it mocked?
import { Post, PrismaClient } from "#prisma/client"
import { Context } from "../context"
import prisma from "lib/prisma"
export class PublishRepository {
private prisma: PrismaClient
constructor(context: Context) {
this.prisma = context.prisma
}
async set_published(post_id: string | string[]): Promise<Post> {
return await prisma.post.update({
where: { id: Number(post_id) },
data: { published: true },
});
}
}

Issues with NextJs SSR and cookies in Apollo

I would like to use cookies for authentication in my nextjs app. I have a bug in my code where the SSR won't work because somewhere in the execution process of the code it does not find the cookie on the first render of the page so it will throw an error. I have played with the code a lot now and have gotten it to a state where the data will eventually load but will not be a SSR page. Has anyone else dealt with this problem?
I am using next, apollo client and apollo server express.
When you do an SSR, the code runs on the server. The cookies you added in browser are not available as default. You can access then in getInitialProps or getServerSideProps via req.headers.cookie and pass it to the authentication code again.
Alternately, you can use an npm module like react-cookie https://www.npmjs.com/package/react-cookie which support isomorphic cookies. More examples on integration are available on the link.
We can custom the headers before sending.
Please check my full answer at this link https://github.com/apollographql/apollo-client/issues/5089#issuecomment-749301669
async function getHeaders(ctx) {
if (ctx?.req?.cookies) {
const cookieItems = []
for (let key of Object.keys(ctx?.req?.cookies)) {
cookieItems.push(`${key}=${ctx.req.cookies[key]}`)
}
return {
cookie: cookieItems.join('; ')
}
}
return {
}
}
WithApollo.getInitialProps = async (ctx) => {
const { AppTree } = ctx
// Initialize ApolloClient, add it to the ctx object so
// we can use it in `PageComponent.getInitialProp`.
const apolloClient = (ctx.apolloClient = initApolloClient(null, await getHeaders(ctx)))
// Run wrapped getInitialProps methods
let pageProps = {}
if (PageComponent.getInitialProps) {
pageProps = await PageComponent.getInitialProps(ctx)
}
............
}
}

Next.js returns 500: internal server error in Production

Created a next.js full stack application. After production build when I run next start it returns 500 : internal server. I'm using environment varibles for hitting api.
env.development file
BASE_URL=http://localhost:3000
It was working fine in development
service.ts
import axios from 'axios';
const axiosDefaultConfig = {
baseURL: process.env.BASE_URL, // is this line reason for error?
headers: {
'Access-Control-Allow-Origin': '*'
}
};
const axio = axios.create(axiosDefaultConfig);
export class Steam {
static getGames = async () => {
return await axio.get('/api/getAppList');
};
}
Do you have a next.config.js file?
To add runtime configuration to your app open next.config.js and add the publicRuntimeConfig and serverRuntimeConfig configs:
module.exports = {
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
staticFolder: '/static',
},
}
To get access to the runtime configs in your app use next/config, like so:
import getConfig from 'next/config'
// Only holds serverRuntimeConfig and publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
// Will only be available on the server-side
console.log(serverRuntimeConfig.mySecret)
// Will be available on both server-side and client-side
console.log(publicRuntimeConfig.staticFolder)
function MyImage() {
return (
<div>
<img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" />
</div>
)
}
export default MyImage
I hope this helps.
I dont think you have setup env.
You need to configure it for it to work. Try it without it and it should work fine!

Resources