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

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?

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");
},
});

Current User in Parse Cloud Code is undefined

I am unable to fetch the current user in my cloud code:
Parse.Cloud.beforeSave('ChatConversation', async (request) => {
const Inbox = Parse.Object.extend("ChatInbox");
const query = new Parse.Query(Inbox);
const user = request.user;
await user.fetch({useMasterKey: true});
const userId = user.get('username');
const inboxId = request.object.get('inbox').id;
query.equalTo('objectId', inboxId );
return query.find().then(async function(res){
const result = res[0];
result.remove("whosTyping", userId);
await result.save();
});
});
And in my flutter debug this is the error output:
flutter: ╭-- Parse Response
Class: sendMessage
Function: ParseApiRQ.execute
Status Code: 141
Type: ScriptError
Error: Cannot read properties of undefined (reading 'fetch')
What am I doing wrong in here? Am I lacking? Please help me out! Thank you so much!

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

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.

mongodb jest error ReferenceError: You are trying to `import` a file after the Jest environment has been torn down

I am trying to test basic mongoDB operation using Jest.
it('should insert a record into collection', async () => {
const users = await db.collection('mariochar');
const mockUser = { name: 'marioChar3'};
await users.insertOne(mockUser);
const insertedUser = await users.findOne({name: 'marioChar3'});
expect(insertedUser).toEqual(mockUser);
});
If I use the default Jest suggested template as above, tests are passing correctly and records can also be seen in the database.
However, since I was learning from this youtube tutorial, I tried to test the Schema directly as shown in the video like this:
it('should insert a mario into collection', async () => {
const MarioCharSchema = new Schema({
name: String,
weight: Number
})
const MarioChar = await mongoose.model('mariochar', MarioCharSchema)
const char = await new MarioChar({ name: "Mario" })
char.save()
console.log(char.isNew)
expect(char.isNew).toBeTruthy()
});
I get the error: ReferenceError: You are trying toimporta file after the Jest environment has been torn down.
After viewing few posts in stackoverflow, I added the fake timer and I am posting the complete code below. It did not get rid of the error.
My second question is that even though Jest shows the above error and also npm ERR! Test failed. See above for more details., it shows the test as passed. Is there a way to report it as failed instead since it is easy to mistake it as passed when there will be a lot of tests?
const { MongoClient } = require('mongodb');
const mongoose = require('mongoose')
const Schema = mongoose.Schema
jest.useFakeTimers()
describe('insert', () => {
let connection;
let db;
beforeAll(async () => {
jest.useFakeTimers()
connection = await MongoClient.connect("mongodb://localhost/testaroo", {
useNewUrlParser: true,
useUnifiedTopology: true
});
db = await connection.db();
});
afterAll(async () => {
await connection.close();
});
it('should insert a mario into collection', async () => {
const MarioCharSchema = new Schema({
name: String,
weight: Number
})
const MarioChar = await mongoose.model('mariochar', MarioCharSchema)
const char = await new MarioChar({ name: "Mario" })
char.save()
expect(char.isNew).toBeTruthy()
});
});
jest.config.js
module.exports = {
"preset": '#shelf/jest-mongodb',
"timers": "fake",
"testEnvironment": "node"
};
package.json
...
"dependencies": {
"mongoose": "^5.9.18"
},
"devDependencies": {
"#shelf/jest-mongodb": "^1.1.5",
"jest": "^26.0.1"
}
...
full error:
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
at model.Document.$__getAllSubdocs (node_modules/mongoose/lib/document.js:2890:37)
at _getPathsToValidate (node_modules/mongoose/lib/document.js:2159:23)
at model.Document.$__validate (node_modules/mongoose/lib/document.js:2314:23)
at node_modules/kareem/index.js:369:33
at node_modules/#jest/fake-timers/build/legacyFakeTimers.js:496:18
PASS test/saving.test.js

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()