Error <path> attribute d: Expected number, "MNaN,NaN\n A32.5,…" - mongodb

Error: attribute d: Expected number, "MNaN,NaN\n A32.5,…". bundle.js:16703
I seem to be getting this error after calling a function (getInfoById(id)).
useEffect(() => {
async function fetchData() {
const realm_id = //id omitted
const app = new Realm.App({ id: realm_id });
const credentials = //credentials omitted
try {
const user = await app.logIn(credentials);
debugger;
await user.functions
.getInfoById(id)
.then((result) => setInfo(result));
} catch (error) {
console.log("This went wrong: ", error);
}
}
fetchData();
}, [id]);
I have looked up this error and all I can find online is that it looks like it might be an issue with nested data. But the result is an object, as expected, so I can't figure out what is happening. Everything is working like I expect, I'm just trying to clear out/ understand this error.

Related

async/await method throws exception -type int is not a subtype of bool

I am calling a graphql endpoint which returns success, but I do get an exception on the calling method.
Here is my calling method -
await AmplifyInstance()// this is where I get the exception. Snip below
.createUserOnAzureCosmosDB(user)
.then((result) {
print(result['data']['userPhoneNumber']);
_intlPhoneFieldController.text =
(result['data']['userPhoneNumber'].toString())
.substring(1);
_incrementStep('continueOnProfilePictureWidget');
});
Here is the called method -
Future<dynamic> createUserOnAzureCosmosDB(User user) async {
HttpLink link = GlobalVariables().graphqlEndpoint;
GraphQLClient graphQlClient = GraphQLClient(
link: link,
cache: GraphQLCache(
store: InMemoryStore(),
),
);
try {
QueryResult mutationResult = await graphQlClient.mutate(
//Mutation query here
if (mutationResult.data?['createUser'] != null) {
print('Created user on Cosmos DB');
registerUserStatus['result'] = true;
registerUserStatus['data'] = mutationResult.data?['createUser'];
}
} on ApiException catch (e) {
print('Mutation failed: $e');
registerUserStatus['result'] = false;
registerUserStatus['errorMessage'] = e.message;
}
return registerUserStatus;
}
And the returned registerUserStatus is just an array -
var registerUserStatus = {};
Here is the exception -
UPDATE eamirho3ein
Here is the result of print("result=$result);
I/flutter (14224): result = {result: true, data: {__typename: User, partitionKey: user, userPhoneNumber: 14160000000, userDisplayName: testuser, avatarUrl: www.url.com, createdAt: Today}}
This is not actually an answer, but rather a way to find the answer more easily yourself:
then chains make it increasingly hard to find your problem, because the compiler/debugger/IDE has a harder time pointing you to it. So don't do it.
With async/await available from the beginning, there never has been a reason to use then in any Dart program.
await AmplifyInstance().createUserOnAzureCosmosDB(user).then((result) {
Is equivalent to just writing:
final result = await AmplifyInstance().createUserOnAzureCosmosDB(user);
And then continuing on with the code you had put in the lambda function in the then part. Obviously, you need to remove the closing bracket somewhere too now.
This way, your error will actually pop up where it happens, not at the await of a huge chain that leaves you wondering what the problem might be.

Always throwing an error even when getting valid data

I'm doing api calls using dio, also I'm using freeze to get the data as follow:
#freezed
class NetworkResponse with _$NetworkResponse {
const factory NetworkResponse.success(Map<String, dynamic> data) = Ok;
const factory NetworkResponse.error(String message)= ERROR;
const factory NetworkResponse.loading(String message)= LOADING;
}
Whenever I get the data from the api, im getting a valid response, but its not returned, instead its throwing an error message from outside:
Future <ReasonsForMeditationModel>getMeditationReasons() async {
var data = await Api().apiCall("reference/reasonsformedication", null, null, RequestType.get);
data?.mapOrNull(success: (data) {
var responseData = data.data;
var reasons = ReasonsForMeditationModel.fromJson(responseData["List"]);
print(reasons);
return reasons;
}, error: (error) {
throw error.toString();
}, loading: (loading) {
throw loading;
});
// this is been thrown every time, knowing that im getting a valid response data and it's been printed, but not returned.
throw "error";
}
im using this future inside a futureBuilder.
but I couldn't figure out the issue.
NOTE: the snapshot values inside the future builder are null
AsyncSnapshot<dynamic>(ConnectionState.done, null, null, null)

Error [ERR_HTTP_HEADERS_SENT] : Can't figure out the multipe requests

I have this error : Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. From my understanding, the problem is that I am trying to send more than one response to the same http request. My instinct tell me that it’s this part that messes up :
catch (err) {
res.status(400).json(err);
}
Because if no user/password found in the DB, we already send status(400). Am I right ? More importantly (and that’s what drives me crazy), I am following a YT tuto and his code is exactly like mine, yet his seems to be working without any problem.
My code :
const router = require("express").Router();
const User = require("../models/Users");
const bcrypt = require("bcrypt");
//LOGIN
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ username: req.body.username });
!user && res.status(400).json("Wrong credentials!");
const validated = await bcrypt.compare(req.body.password, user.password);
!validated && res.status(400).json("Wrong credentiaaaals!");
const { password, ...others } = user._doc;
res.status(200).json(others);
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router;
His code :
//LOGIN
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ username: req.body.username });
!user && res.status(400).json("Wrong credentials!");
const validated = await bcrypt.compare(req.body.password, user.password);
!validated && res.status(400).json("Wrong credentials!");
const { password, ...others } = user._doc;
res.status(200).json(others);
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router;
Am I doing something wrong ? Is my reflexion bad ? Thanks !
You are right, your code is trying to send data to the client multiple times. The issue is that after the call .json("Wrong credentials!") completed, the write stream to the client will be closed, and you will not be able to send any other data to the client. The framework knows to detect it and show you the bug.
In your code, after the method .json("Wrong credentials!") finishes own execution, your program will continue and will try to execute the next lines...
You just need to add return, so the program will exit the current flow after it sends the response to the client.
const router = require("express").Router();
const User = require("../models/Users");
const bcrypt = require("bcrypt");
//LOGIN
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ username: req.body.username });
if (!user) {
return res.status(400).json("Wrong credentials!"); // without return the code will continue to execute next lines
}
const validated = await bcrypt.compare(req.body.password, user.password);
if (!validated) {
return res.status(400).json("Wrong credentiaaaals!"); // without return the code will continue to execute next lines
}
const { password, ...others } = user._doc;
res.status(200).json(others); // return is not necessary, because there is no cod which will be executed after we back from the json method
} catch (err) {
res.status(500).json(err); // return is not necessary, because there is no cod which will be executed after we back from the json method
}
});
module.exports = router;

Jest mock mongoose.startSession() throws error

i'm implemented transaction in the post method. it was work fine. But now I have to update unit test case for that method. I tried to mock startSession() and startTransaction() to check toHaveBeenCalled.But while running test case i got like MongooseError: Connection 0 was disconnected when calling startSession``. I am new to that so i don't know how to mock that?.
Method:
static post = (funcCall: Promise<Document>) => async (response: Response, fields?: string[]) => {
const session = await startSession();
session.startTransaction();
try {
const dbResponse = await funcCall; // model.save(request.body)
// commit the changes if everything was successful
await session.commitTransaction();
success(pick(dbResponse, fields ? fields : ['_id']), 201)(response);
} catch (error) {
// this will rollback any changes made in the database
await session.abortTransaction();
throwError(error);
} finally {
// ending the session
session.endSession();
}
};
My Test case:
it('should perform post when valid parameters is passed.', async () => {
// Preparing
const mockSaveReturn = {
_id: objectID,
test_name: 'sample',
};
jest.spyOn(mongoose, 'startSession')
const spySave = jest.spyOn(modelPrototype.prototype, 'save').mockReturnValueOnce(mockSaveReturn);
const document = new modelPrototype(mockSaveReturn);
// Executing
await post(document.save())(response as Response);
expect(response.send).toHaveBeenCalledWith({ _id: '54759eb3c090d83494e2d804' });
expect(spySave).toHaveBeenCalled();
// Cleaning
spySave.mockClear();
});

Cannot read property innerText of null for valid selector using playwright

This script is supposed to retrieve the innerText of a DOM element, the elements selector is
('div[class=QzVHcLdwl2CEuEMpTUFaj]') and I've hand-tested the selector and called the getSharePrice function in the REPL which also works.
const { chromium } = require('playwright');
const util = require('util');
const setTimeoutPromise = util.promisify(setTimeout);
(async () => {
const userDataDir = 'path'
const browser = await chromium.launchPersistentContext(userDataDir, {headless: false });
const page = await browser.newPage();
await page.goto('https://robinhood.com', {timeout: 60000, waitUntil: 'domcontentloaded'});
await getSharePrice(page)
await setTimeoutPromise(1000);
await browser.close();
})();
async function getSharePrice(page) {
const price = await page.evaluate(() => {
return {
price: document.querySelector('div[class=QzVHcLdwl2CEuEMpTUFaj]').innerText.replace(/\D/g,'')
}
});
console.log(price)
}
for some reason, I am getting a (node:59324) UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: Cannot read property 'innerText' of null error, not sure why.
The only thing that I could come up with is that the element hasn't been loaded yet, causing it to evaluate to null which is why innerText can't be called.
adding await page.waitForSelector('div[class=QzVHcLdwl2CEuEMpTUFaj]') before my evaluate block fixed this. Looks like the issue was caused by the element not being loaded yet