Keep getting ReferenceError: fter is not defined - referenceerror

My filter function sends in the two parameters I want to be used in my filter.sql but to no avail it always returns this. At some point I cannot figure out my parameters does not get to the controller file. It is defined before sent off to the endpoint but as it tries to use that value in the controller function it says not defined.
First filter function:
handleFilter() {
console.log(this.state.filter);
console.log(this.state.filterText);
if (this.props.searchText === "") {
axios
.post("/api/filter", { fText: this.state.filterText, fter:
this.state.filter })
.then(response => {
this.props.updateCSR(response.data);
updateFPO(this.props.filterPopout === false ? true : false);
});
} else {
axios
.post(
"/api/sfilter",
{
fText: this.state.filterText,
fter: this.state.filter,
sText: this.props.searchText
}
)
.then(response => {
this.props.updateCSR(response.data);
updateFPO(this.props.filterPopout === false ? true : false);
});
}
}
Endpoint:
app.post("/api/filter", ic.filter);
app.post("/api/sfilter", ic.sfilter);
Filter in Controller:
filter: (req, res, next) => {
const { filter, filterText } = req.body;
const dbInstance = req.app.get("db");
dbInstance
.filter([fter, fText])
.then(resp => {
res.status(200).send(resp);
})
.catch(() => res.status(500).send());
},
sfilter: (req, res, next) => {
const { fter, fText, sText } = req.body;
const dbInstance = req.app.get("db");
dbInstance
.sfilter([fter, fText, sText])
.then(resp => {
res.status(200).send(resp);
})
.catch(() => res.status(500).send());
}
The error on the console for the front end is
POST http://localhost:3000/api/filter 500 (Internal Server Error)
dispatchXhrRequest # xhr.js:178
xhrAdapter # xhr.js:12
dispatchRequest # dispatchRequest.js:52
Promise resolved (async)
request # Axios.js:58
Axios.(anonymous function) # Axios.js:78
wrap # bind.js:9
handleFilter # Filter.js:33
onClick # Filter.js:79
callCallback # react-dom.development.js:1299
invokeGuardedCallbackDev # react-dom.development.js:1338
invokeGuardedCallback # react-dom.development.js:1195
invokeGuardedCallbackAndCatchFirstError # react-dom.development.js:1209
executeDispatch # react-dom.development.js:1432
executeDispatchesInOrder # react-dom.development.js:1454
executeDispatchesAndRelease # react-dom.development.js:1969
executeDispatchesAndReleaseTopLevel # react-dom.development.js:1980
forEachAccumulated # react-dom.development.js:1946
processEventQueue # react-dom.development.js:2139
runEventQueueInBatch # react-dom.development.js:2151
handleTopLevel # react-dom.development.js:2161
handleTopLevelImpl # react-dom.development.js:1800
batchedUpdates # react-dom.development.js:13238
performFiberBatchedUpdates # react-dom.development.js:1646
stackBatchedUpdates # react-dom.development.js:1637
batchedUpdates # react-dom.development.js:1651
batchedUpdatesWithControlledComponents # react-dom.development.js:1664
dispatchEvent # react-dom.development.js:1874
createError.js:16 Uncaught (in promise) Error: Request failed with status code 500
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
What is going on here? I have had this problem in other places but I cannot ignore it now. I have to fix it but it is not complying!!
Thanks for your time!!!!!

I'm not sure, maybe you need to change to the following? :
dbInstance
.filter([filter, filterText])
.then(resp => {
res.status(200).send(resp);
})
.catch(() => res.status(500).send());
},
Since it looks to me like at that point fter and fText aren't defined yet, but filter and filterText are so you probably meant to use them.

Related

Cannot POST when sending request in Postman

I am having a small issue. I am trying to send a request in Postman, but I receive "
Cannot POST /api/logTemp/1/25
"
Here is my app.js:
const express = require('express')
const bodyParser = require('body-parser')
const cors= require('cors')
const fs= require('fs')
const path= require('path')
const morgan = require('morgan')
const router = require('./routes/route')
const app = express()
app.use(cors())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false}))
// parse application/json
app.use(bodyParser.json())
app.use(morgan('dev'))
//create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, '/logs/access.log'), {flags: 'a'})
//setup the logger
app.use(morgan('combined', {stream: accessLogStream}))
app.use(router)
app.get('/', (req, res) => {
res.send('Hello World!')
})
const port = 3000
//app.listen(process.env.PORT || port, (err) => {
app.listen(port, () => {
console.log('Server started running on :' + port)
})
and here is my controller file:
const { getEnabledCategories } = require('trace_events');
const mysql = require('../database/db')
class MainController {
async logTemp(req, res){
console.log(req.params.temperature)
console.log(req.params.deviceID)
if(req.params.deviceID != null && req.params.temperature != null){
let deviceID = req.params.deviceID
let temperature = req.params.temperature;
var sql = `insert into log_temp (log_date, device_id, temp) values (now(),${deviceID}, ${temperature});`
mysql.query(sql, (error,data,fields) => {
if(error){
res.status(500)
res.send(error.message)
} else{
console.log(data)
res.json({
status: 200,
message: "Log uploaded successfully",
affectedRows: data.affectedRows
})
}
})
} else {
res.send('Por favor llena todos los datos!')
}
}
async getLogs(req, res){
console.log("Get Logs")
console.log(req.params.deviceID)
if(req.params.deviceID!=null){
let deviceID = req.params.deviceID;
var sql = `SELECT * FROM log_temp where device_id=${deviceID}`
mysql.query(sql, (error, data, fields) => {
if(error) {
res.status(500)
res.send(error.message)
} else {
console.log(data)
res.json({
data
})
}
})
}
}
}
const tempController = new MainController()
module.exports = tempController;
The code above was made in Visual Studio. It is odd because getLogs does work but logTemp does not. What I intend to do with logTemp is add a new value (which is the value temperature) to MySQL database. The connection to the database worked just fine, as well as localhost. If you need any more info in order to help me find a solution, please let me know and I will be more than happy to provide it. Also, i'm sorry for any grammar errors, english is not my first language :)

Assertion error whilst running truffle test

I got an error while running truffle test on a smart contract, can anyone help me with this?
const KryptoBird = artifacts.require("KryptoBird");
// check for chai
require('chai')
.use(require('chai-as-promised'))
.should()
contract('KryptoBird', (accounts) => {
let contract
before( async () => {
contract = await KryptoBird.deployed()
})
describe('deployment', async() => {
it("deploys successfully", async () => {
const address = contract.address;
assert.notEqual(address, '')
assert.notEqual(address, null)
assert.notEqual(address, undefined)
assert.notEqual(address, 0x0)
})
it('has a name', async() => {
const name = await contract.name()
assert.equal(name, 'KryptoBird')
})
it('has a symbol', async() => {
const symbol = await contract.symbol()
assert.equal(symbol, 'KBIRDZ')
})
})
describe('minting', async ()=> {
it('creates a new token', async ()=> {
const result = await contract.mint('https...1')
const totalSupply = await contract.totalSupply()
assert.equal(totalSupply, 1)
const event = result.logs[0].args
assert.equal(event._from, '0x0000000000000000000000000000000000000000', 'from is the contract')
assert.equal(event._to, accounts[0], 'to is msg.sender')
await contract.mint('https...1').should.be.rejected
})
})
})
this is my code, and when I run it, it gives me an error that I don't understand
this is the error:
1 ) Contract : KryptoBird
minting
creates a new token :
AssertionError : expected promise to be rejected but it was fulfilled with { Object ( tx , receipt , ... ) }
error message
please help me, I've been stuck on this for a day.
heres my smart contract code, if u could help me
thanks a lot! :
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import './ERC721Connecter.sol';
contract KryptoBird is ERC721Connecter {
string[] public kryptoBirdz;
mapping(string => bool) _kryptoBirdzExists;
function mint(string memory _kryptoBird) public {
require(!_kryptoBirdzExists[_kryptoBird],
'Error - kryptoBird already exists');
// this is deprecated - uint _id = KryptoBirdz.push(_kryptoBird);
kryptoBirdz.push(_kryptoBird);
uint _id = kryptoBirdz.length - 1;
// .push no logner returns the length but a ref to the added element
_mint(msg.sender, _id);
}
constructor() ERC721Connecter('KryptoBird','KBIRDZ')
{}
}
The problem is not you are not adding entry into the _kryptoBirdzExists mapping. before you mint, you are checking this condition
require(!_kryptoBirdzExists[_kryptoBird],
So after minting, you should be updating the mapping
_kryptoBirdzExists[_kryptoBird]=true;
Your test is not failing because you never added the 'https...1' to the mapping so require stament was passing so you were minting again

jest.spyOn mock return value not returning value

The code I'm trying to test:
const utils = require('../utils/utils');
let imageBuffer;
try {
imageBuffer = await utils.retrieveImageFromURI(params)
console.log(imageBuffer) // comes back as undefined when I mock the utils.retreieveImageFromURI
if (!imageBuffer || imageBuffer.length < 1024) {
throw new Error(`Retrieve from uri (${params.camera.ingest.uri}) was less than 1kb in size - indicating an error`)
}
console.log(`${params.camera.camId} - Successful Ingestion from URI`);
} catch (err) {
reject({ 'Task': `Attempting to pull image from camera (${params.camera.camId}) at ${params.camera.ingest.uri}`, 'Error': err.message, 'Stack': err.stack })
return;
}
Specifically, I'm trying to mock the utils.retrieveImageFromURI function - which has API calls and other things in it.
When I try to mock the function using spyOn I am trying it like so:
describe("FUNCTION: ingestAndSave", () => {
let fakeImageBuffer = Array(1200).fill('a').join('b'); // just get a long string
console.log(fakeImageBuffer.length) //2399
let retrieveImageFromURISpy
beforeAll(() => {
retrieveImageFromURISpy = jest.spyOn(utils, 'retrieveImageFromURI').mockReturnValue(fakeImageBuffer)
})
test("Will call retrieveImageFromURI", async () => {
await ingest.ingestAndSave({camera:TEST_CONSTANTS.validCameraObject, sourceQueueURL:"httpexamplecom", receiptHandle: "1234abcd"})
expect(retrieveImageFromURISpy).toHaveBeenCalledTimes(1)
})
afterEach(() => {
jest.resetAllMocks()
})
afterAll(() => {
jest.restoreAllMocks()
})
})
When I do this, I get a console log that imageBuffer (which is supposed to be the return of the mocked function) is undefined and that, in turn, triggers the thrown Error that "Retrieve from uri ...." ... which causes my test to fail. I know I could wrap the test call in a try/catch but the very next test will be a "does not throw error" test... so this needs to be solved.
It's not clear to me why the mockReturnValue isn't getting returned.
Other steps:
I've gone to the REAL retrieveImageFromURI function and added a console log - it is not running.
I've changed mockReturnValue to mockImplementation like so:
retrieveImageFromURISpy = jest.spyOn(utils, 'retrieveImageFromURI').mockImplementation(() => {
console.log("Here")
return fakeImageBuffer
})
And it does NOT console log 'here'. I'm unsure why not.
I have also tried to return it as a resolved Promise, like so:
retrieveImageFromURISpy = jest.spyOn(utils, 'retrieveImageFromURI').mockImplementation(() => {
console.log("Here")
return Promise.resolve(fakeImageBuffer)
})
Note, this also doesn't console log.
I've also tried to return the promise directly with a mockReturnValue:
`retrieveImageFromURISpy = jest.spyOn(utils, 'retrieveImageFromURI').mockReturnValue(Promise.resolve(fakeImageBuffer)`)

Unable to setup AWS-amplify MFA - issue with the Auth.confirmSignIn function

I'm having a problem with my adding MFA to my site which manages authentication with AWS Amplify.
I've followed the example here and created the code below to handle both users who have MFA enabled, and those that don't.
const Signin = props => {
const { classes, onStateChange, history } = props;
const [inputs, setInputs] = useState({
username: '',
password: '',
});
const [currentStep, setCurrentStep] = useState(1)
const [userObject, setUserObject] = useState({})
const [authCode, setauthCode] = useState({code: ''})
const onSignIn = async (e) => {
const username = inputs.username.toLowerCase()
await Auth.signIn({
username, // Required, the username
password: inputs.password, // Optional, the password
}).then(user => {
if (user.preferredMFA === 'SOFTWARE_TOKEN_MFA'){
setUserObject(user)
setCurrentStep(2)}
else{
onStateChange('signedIn', {})
history.push('/dashboard');
}
})
.catch(err => {
showAlert(err.message)
if (err.code === 'PasswordResetRequiredException') {
onStateChange('forgotPassword')
history.push('/forgotpassword');
}
})
}
const MfaSignIn = async (e) => {
const user=userObject
await Auth.confirmSignIn(
user,
authCode.code,
user.preferredMFA
).then(user => {
onStateChange('signedIn', {})
history.push('/dashboard');
})
.catch(err => {
showAlert(err.message)
if (err.code === 'PasswordResetRequiredException') {
onStateChange('forgotPassword')
history.push('/forgotpassword');
}
})
If MFA is not enabled the login page will call the onSignIn function then log them in. If MFA is enabled the user object returned from the signin function will return the value "SOFTWARE_TOKEN_MFA" for the preferredMFA key, and a second page will load which allows the user to enter their MFA code, which is handled by the MfaSignIn function.
No MFA works fine, however when attempting to use the MfaSignIn function as is I get "Missing required parameter Session"
the Session key of the user object returned by onSignIn has a value of null, and there's no mention of it needing to be added from the docs. Ive tried adjusting this function to
const MfaSignIn = async (e) => {
e.preventDefault(authCode.code);
const session= Auth.currentSession().then(data=> {return data})
const token = await session.then(data=>{return data.getAccessToken()})
const user=userObject
user.Session=token.jwtToken
await Auth.confirmSignIn(
user,
authCode.code,
user.preferredMFA
).then(user => {
onStateChange('signedIn', {})
history.push('/dashboard');
})
.catch(err => {
showAlert(err.message)
if (err.code === 'PasswordResetRequiredException') {
onStateChange('forgotPassword')
history.push('/upgrade');
}
})
}
Where I call the Auth.currentSession method and add the data from there to the Session value in the user object. Adding the whole object returns the error-
"Start of structure or map found where not expected."
- seems to need a string not a map object
I've tried adding each of the three JWT token strings that are found in the currentSession object, along with the result of the getAccessToken as in the example above. All return the error
"Invalid session provided"
I'm at a loss at what I need to give the Auth.confirmSignIn to let the user sign in- I appear to be doing everything correctly as per the docs.
Any ideas?

ReactJs - test multiple calls in redux-saga with expectSaga

I'm using expectSaga ('redux-saga-test-plan') to test one of my sagas and I'm wondering how to test multiple calls made within the same saga.
Sagas.js
export function* fetchSomething(arg){
const response = yield call(executeFetch, arg);
if(response.status === 200){
// trigger success action
} else if (response.status >= 400){
const errResp = yield response.json();
const errorCode = yield call(sharedUtilToExtractErrors, errResp);
yield put(
{ type: 'FETCH_FAILED', errorMessage: UI_ERR_MSG, errorCode }
);
}
}
Unit test
import { expectSaga } from 'redux-saga-test-plan';
describe('fetchSomething', () => {
// positive paths
// ..
// negative paths
it('fetches something and with status code 400 triggers FETCH_FAILED with error message and extracted error code', () => {
const serverError = { message: 'BANG BANG BABY!' };
const koResponse = new Response(
JSON.stringify(serverError),
{ status: 400, headers: { 'Content-type': 'application/json' } }
);
return expectSaga(fetchSomething)
.provide(
{
call: () => koResponse,
call: () => serverError.message,
}
)
.put({
type: 'FETCH_FAILED', errorMessage: UI_ERR_MSG, serverError.message
})
.run();
})
})
Clearly having the "call" attribute twice in the same object passed in to provide() doesn't work but also calling provide() twice doesn't do the trick. Any suggestions?
Thanks
This is how you can provide multiple calls according to the documentation:
.provide([ // this external array is actually optional
[call(executeFetch, arg), koResponse],
[call(sharedUtilToExtractErrors, serverError), serverError.message],
])
or if you're lazy and don't want to specify the arguments:
import * as matchers from 'redux-saga-test-plan/matchers';
.provide(
[matchers.call.fn(executeFetch), koResponse],
[matchers.call.fn(sharedUtilToExtractErrrors), serverError.message],
)
Neither of these two worked for me though as for some reason it was not mocking out the dependencies and still calling them caused errors.
I solved using a dynamic provider:
.provide({
// select(effect, next) { return 'something-for-a-selector' },
call(effect) {
switch(effect.fn.constructor.name) {
case executeFetch.constructor.name: return koResponse;
case sharedUtilToExtractErrors.constructor.name: return serverError.message;
default: throw new Error('Unknown function called in test');
}
}
})