How to inject a stub function when using Hapi.js server.inject - mongodb

I have a hapijs project which is using the hapi-mongodb plugin.
In the handler I am using the hapi-mongodb plugin to make db calls. See below
internals.getById = async (request, h) => {
try {
const db = request.mongo.db;
const ObjectId = request.mongo.ObjectID;
const query = {
_id: ObjectId(request.params.id)
};
const record = await db.collection(internals.collectionName).findOne(query);
//etc.....
I want to be able to test this using server.inject(), but I am not sure how to stub the request.mongo.db and the request.mongo.ObjectID
it('should return a 200 HTTP status code', async () => {
const server = new Hapi.Server();
server.route(Routes); //This comes from a required file
const options = {
method: 'GET',
url: `/testData/1`
};
//stub request.mongo.db and request.mongo.ObjectID
const response = await server.inject(options);
expect(response.statusCode).to.equal(200);
});
Any ideas?

I worked this out and realised that the mongo plugin decorates the server object which can be stubbed.

Related

React-query: invalidateQueries doesn't work

I'm trying to invalidate queries when I create new comment.
const { data: comments } = useQuery("getComments", () => getComments({ originalKind: "NOTICE", originalSeq: id }));
const createCommentMutation = useMutation(postComment, {
onSuccess: async () => {
const queryClient = new QueryClient();
await queryClient.invalidateQueries("getComments");
},
});
The comment is created successfully, but invalidateQueries dose not working.
There is no default options...
every time i create comment, the query will invalidated
If you create a new QueryClient, it will have a new QueryCache, which is not associated with the cached data of your query. That's not how it works, and that's also not what any of the official examples / docs are showing.
What you have to do is get access to the client with useQueryClient() - another hook exported from react-query. This will give you the singleton QueryClient that you have put into the QueryClientProvider:
import { useQueryClient } from '#tanstack/react-query'
const queryClient = useQueryClient()
const createCommentMutation = useMutation(postComment, {
onSuccess: async () => {
await queryClient.invalidateQueries("getComments");
},
});

MongoDB AppService's getAllData not working on my react.js application

My App ID is added to my react.js like that:
import * as Realm from "realm-web";
const REALM_APP_ID = "memeified_data-knivd";
const app = new Realm.App({ id: REALM_APP_ID });
My getAllData works well using the MongoDB App terminal:
But when I use the following code:
const [mainData, setData] = useState(null)
useEffect(() => {
const fetchData = async () => {
const data = await user.functions.getAllData()
setData(data);
}
fetchData()
.catch(console.error);;
}, [])
The code returns this console error:
TypeError: Cannot read properties of null (reading 'functions')
What could go wrong here?

What is cancelToken by axios and how I fix it?

I made a React app and I making requests to the backend using Axios. I created a middleware in my backend for authorization and on the frontend side I'm trying to pass to every call that is made to the backend the auth token if exists in the localStorage. Before I added the logic for that everything worked perfectly, now every time I try to log in or register I get this in the console
TypeError: Cannot read properties of undefined (reading 'cancelToken')
at throwIfCancellationRequested (dispatchRequest.js:12:1)
at dispatchRequest (dispatchRequest.js:24:1)
at async auth.js:6:1
My index.js which handles every call to the backend looks like this:
import axios from 'axios';
const API = axios.create({
baseURL: 'http://localhost:3500'
})
API.interceptors.request.use((req) => {
if (localStorage.getItem('profile')) {
req.headers.Authorization = `Bearer ${JSON.parse(localStorage.getItem('profile')).token}`
}
})
export const fetchHunts = () => API.get('/hunts');
export const createHunt = (newHunt) => API.post('/hunts', newHunt);
export const updateHunt = (id, updatedHunt) => API.patch(`/hunts/${id}`, updatedHunt);
export const deleteHunt = (id) => API.delete(`/hunts/${id}`);
export const signInAdmin = (formData) => API.post('/admins/signinadmin', formData);
export const signUpAdmin = (formData) => API.post('/admins/signupadmin', formData);
Right now I am not logged in so there is no profile in the localStorage. I tried to add this, I found this here on stack overflow but didn't work
const CancelToken = Axios.CancelToken;
instance.interceptors.request.use(req => {
/* some logic */
const CancelToken = Axios.CancelToken;
return {
...req,
cancelToken: new CancelToken((cancel) => cancel('Cancel repeated request'))
};
});
but when I used this it only returned " Cancel repeated request " and did nothing. Do you know how can I fix that? Thank you in advance!
Based on the Axios Documentation - Interceptors, the interceptor function should return the req.
API.interceptors.request.use((req) => {
if(localStorage.getItem('profile')) {
req.headers.Authorization = `Bearer ${JSON.parse(localStorage.getItem('profile')).token}`;
}
return req;
})
My 2cents:
looks like it's easier NOT to make the request in the first place, if user is not authorized =)
Just add a global middleware on frontend to redirect user to auth page.
Here is an example in Vue, but you get the logic.
import { Middleware } from '#nuxt/types';
import { RoutesName } from '~/shared/repository/routes/routes-name';
const auth: Middleware = async (context) => {
const { route, store } = context;
const isAuthorized = store.getters['user/isAuthorized'];
const isAuthPage = route.name === RoutesName.auth;
if (!isAuthorized && !isAuthPage) {
return context.redirect(`/${RoutesName.auth}`);
}
if (isAuthorized && isAuthPage) {
return context.redirect('/');
}
};
export default auth;

Express and MongoDB without Mongoose

This is not so much of a question but more of a consult request. I couldn't find resources to check my method's validity so I would like to hear MongoDB experts' opinion.
I was playing around with MongoDB and came up with this middleware method to pass client to my routes. I have this Express middleware:
const addClientToRequest = async (req, _, next) => {
const client = new MongoClient(uri);
await client.connect();
req.client = client;
next();
};
app.use(addClientToRequest);
After that, I use req.client in my routes to access my database.
app.get("/:id", async (req, res) => {
const client = req.client;
const id = req.params.id;
try {
const data = await client.db("mydb").collection("mycollection").findOne({ id });
if (data) return res.status(200).json(data);
} catch (error) {
return res
.status(500)
.json({ message: "Error fetching requested data", error });
}
return res.status(404).json({ message: "Requested data cannot be found" });
});
What would be a problem in this approach? Is it okay to use MongoDB client like this?
In my experience, we have always defined a separate utility to load a connection pool at the app startup and then reused those connections.
In the above approach, you seem to be creating a new connection for every HTTP request that is made and then not terminating (or) closing the connection. This may be expensive for a large app.
db.util.js
const { MongoClient } = require("mongodb");
const uri = `mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}#localhost:27017/${process.env.DATABASE}?maxPoolSize=2-&w=majority`;
const client = new MongoClient(uri);
const init = async () => {
try {
await client.connect();
console.log("Connected");
} catch (error) {
console.log(error);
}
};
const getClient = () => {
return client;
};
module.exports.init = init;
module.exports.getClient = getClient;
app.js
//Import modules
require("dotenv").config({ path: __dirname + "/.env" });
const express = require("express");
const dogRoutes = require("./routes/dog.routes");
const db = require("./utils/db.util");
// Define PORT for HTTP Server
const PORT = 9900;
// Initialize Express
const app = express();
app.use(express.json());
app.use(dogRoutes);
(async () => {
await db.init();
app.listen(PORT, (err) => {
console.log(`Server is up at localhost ${PORT}`);
});
})();
I think that what you could do is to put the client outside of the middleware, so you doesn't re define it and re connect to it each time a request is done.
To do so, simply define it and connect before the middleware, and in the middleware, set the client as req.mongoClient or how you want to name it.
const client = new MongoClient(uri);
await client.connect(); // if this is outside of an async function, either use an async function like (async () => {..script..})(), either define a variable isClientReady and set it on true after the promise resolved.
const addClientToRequest = (req, _, next) => {
req.client = client;
next();
};
app.use(addClientToRequest);

Connect Apollo with mongodb

I want to connect my Apollo server with my mongoDB. I know there are many examples out there, but I get stuck at the async part and did not found a solution or example for that (that's strange, am I completly wrong?)
I started with the example from next.js https://github.com/zeit/next.js/tree/master/examples/api-routes-apollo-server-and-client .
But the mongodb integration is missing.
My code
pages/api/graphql.js
import {ApolloServer} from 'apollo-server-micro';
import {schema} from '../../apollo/schema';
const apolloServer = new ApolloServer({schema});
export const config = {
api: {
bodyParser: false
}
};
export default apolloServer.createHandler({path: '/api/graphql'});
apollo/schema.js
import {makeExecutableSchema} from 'graphql-tools';
import {typeDefs} from './type-defs';
import {resolvers} from './resolvers';
export const schema = makeExecutableSchema({
typeDefs,
resolvers
});
apollo/resolvers.js
const Items = require('./connector').Items;
export const resolvers = {
Query: {
item: async (_parent, args) => {
const {id} = args;
const item = await Items.findOne(objectId(id));
return item;
},
...
}
}
apollo/connector.js
require('dotenv').config();
const MongoClient = require('mongodb').MongoClient;
const password = process.env.MONGO_PASSWORD;
const username = process.env.MONGO_USER;
const uri = `mongodb+srv://${username}:${password}#example.com`;
const client = await MongoClient.connect(uri);
const db = await client.db('databaseName')
const Items = db.collection('items')
module.exports = {Items}
So the problem is the await in connector.js. I have no idea how to call this in an async function or how to provide the MongoClient on an other way to the resolver. If I just remove the await, it returns – obviously – an pending promise and can't call the function .db('databaseName') on it.
Unfortunately, we're still a ways off from having top-level await.
You can delay running the rest of your code until the Promise resolves by putting it inside the then callback of the Promise.
async function getDb () {
const client = await MongoClient.connect(uri)
return client.db('databaseName')
}
getDb()
.then(db => {
const apollo = new ApolloServer({
schema,
context: { db },
})
apollo.listen()
})
.catch(e => {
// handle any errors
})
Alternatively, you can create your connection the first time you need it and just cache it:
let db
const apollo = new ApolloServer({
schema,
context: async () => {
if (!db) {
try {
const client = await MongoClient.connect(uri)
db = await client.db('databaseName')
catch (e) {
// handle any errors
}
}
return { db }
},
})
apollo.listen()