express path issues when using same logic on diffrent paths - express

id path is working (I get the result from the json), but even though pokeName uses the same logic, I dont get any data from it. What have we missed?
JSON: https://github.com/Biuni/PokemonGO-Pokedex/blob/master/pokedex.json
const Pokemons = mongoose.model('Pokemons', {
id: Number,
name: String,
type: Array,
})
_____
app.get('/pokemons', async (req, res) => {
try {
if (!allPokemons) {
res.status(404).send('No data to show')
} else {
res.json(allPokemons.pokemon) /*[1].name*/
}
} catch (error) {
res.status(400).json({ error: 'Not found' })
}
})
_____
app.get('/pokemons/id/:id', async (req, res) => {
const { id } = req.params
const pokemon = allPokemons.pokemon.find((item) => item.id === +id)
try {
if (!pokemon) {
res.status(404).send('No pokemon found with this ID')
} else {
res.json(pokemon)
}
} catch (error) {
res.status(400).json({ error: 'Not found' })
}
})
_____
app.get('/pokemons/name/:pokeName', async (req, res) => {
const { pokeName } = req.params
const pokemon = allPokemons.pokemon.find((item) => item.name === +pokeName)
try {
if (!pokemon) {
res.status(404).send('No pokemon found with this name')
} else {
res.json(pokemon)
}
} catch (error) {
res.status(400).json({ error: 'Not found' })
}
})

You're trying to convert the name to a number (presumably because id is a number, and you copied its code):
item.name === +pokeName
But it's not, so this will result in a NaN. Remove the +:
item.name === pokeName

Related

Setting data from firebase with useState is returning undefined

I am trying to set data for verification purposes. I do set the data then get undefined which is disturbing to me, I've tried to parse it in different shapes, I've used useCallback hook and without any real benefit
const getUserPhone = useCallback(async () => {
console.log('user phone is requested');
await firebase
.database()
.ref(`users/${login.uid}`)
.once(
'value',
async (data) => {
if (data.exists()) {
console.log('found');
await setUserData(data.toJSON());
console.log('data has been set');
} else {
Alert.alert('User not found');
return;
}
},
// I've tried .get() from firebase and
//.then(async (data: IUser) => {await setUserData(data.toJSON()})
// It does the same.
)
.catch((error) => {
return console.error(error);
});
}, [login.uid]);
const handleVerification = useCallback(async () => {
if (alreadyRequested) {
return;
}
await getUserPhone();
try {
console.log(userData); // undefined
if (!userData?.phoneNumber) {
console.log('no phone number is here');
return;
}
...
} catch ...
}, [alreadyRequested, getUserData, userData?.phoneNumber])
Output:
user phone is requested
found
data has been set
undefined
no phone number is here

update query in sqlite failed

I send my object by post request with postman then in the backend with node js recive it and update my table but it return sqlerror on string in object and no problem on integer !
1 - my obj in postman => {
"id" : 3,
"controlsCode":123456,
"controlsName" : "hamed"
}
2 - my code in node =>
async editControls(req, res) {
try {
const { id, controlsCode, controlsName } = req.body;
const query = `update controls set controlCode=${controlsCode} , controlName=${controlsName} where id =${id}`;
await sequelize
.query(query)
.then((item) =>
this.response({ res, message: "ok", data: controlsCode })
)
.catch((error) => console.log(error.message));
} catch (error) {
console.log(error.message);
}
}
3-error in node js =>
SQLITE_ERROR: no such column: hamed
You need single quotes around the string literal:
try {
const { id, controlsCode, controlsName } = req.body;
const query = `update controls set controlCode=${controlsCode} , controlName='${controlsName}' where id =${id}`;
await sequelize
.query(query)
.then((item) =>
this.response({ res, message: "ok", data: controlsCode })
)
.catch((error) => console.log(error.message));
} catch (error) {
console.log(error.message);
}

Unknown field found while parsing JSONEachRow format Click house

I'm getting this error
I'm inserting the data into the Clickhouse and i get this error because some of fields are null.
Unknown error field: Code: 117. DB::Exception: Unknown field found while parsing JSONEachRow format: SharesStats: (at row 1): While executing JSONEachRowRowInputFormat. (INCORRECT_DATA) (version 21.11.6.7 (official build))
const Clickhouse = require('#apla/clickhouse');
const { default: axios } = require('axios');
const stockCode = require('./stockCode');
const clickhouse = new Clickhouse({
host: 'localhost',
port: 8123,
username: 'default',
password: '',
dataObjects: true,
queryOptions: {
database: 'stocks'
}
});
const indexStream = clickhouse.query(
'INSERT INTO test2',
{
format: 'JSONEachRow'
},
(err) => {
if (err) {
return console.error(err);
}
}
);
const fetchDataFundamentals = async (stock) => {
try {
const { data: response } = await axios.get(
`https://eodhistoricaldata.com/api/fundamentals/${stock}?api_token=${apiKey}&fmt=json`
);
const nestedFields = [
'SharesStats',
'Technicals',
'SplitsDividends',
'outstandingShares',
'Earnings',
'Financials'
];
const data = {
...response.General,
...response.Highlights,
...response.Valuation,
...response.Holders,
...response.InsiderTransactions,
SharesStats: response.SharesStats,
Technicals: response.Technicals,
SplitsDividends: response.SplitsDividends,
outstandingShares: response.outstandingShares,
Earnings: response.Earnings,
Financials: response.Financials
};
Object.keys(data).forEach((key) => {
if (nestedFields.includes(key)) {
data[key] = Object.keys(data[key]).map((nestedKey) => {
if (!data[key][nestedKey]) {
data[key][nestedKey] = 0;
} else if (typeof data[key][nestedKey] === 'object') {
data[key][nestedKey] = JSON.stringify(data[key][nestedKey]);
}
return data[key][nestedKey];
});
} else if (!data[key]) {
delete data[key];
} else if (typeof data[key] === 'object') {
data[key] = JSON.stringify(data[key]);
}
});
console.log(data);
indexStream.write(data);
indexStream.end();
} catch (error) {
console.error(error.message);
}
};
// Promise.all(stockCode.map((code) => fetchDataFundamentals(code)))
// .then(() => {
// indexStream.end();
// console.log('Fundametals data inserted');
// })
// .catch((err) => {
// console.log(err.message);
// });
try {
fetchDataFundamentals('1010.SR');
} catch (error) {
console.error(error.message);
}

Changing the collection based on the request type

This controller accepts the form and updates the data.
export const createPost = async (req, res) => {
const { title, message, selectedFile, creator, tags } = req.body;
const newPostMessage = new OrangeModel ({ title, message, selectedFile, creator, tags })
try {
await newPostMessage.save();
res.status(201).json(newPostMessage );
} catch (err) {
res.status(409).json({ message: err.message });
}
}
I want to change the collection type based on the request.
when the request is from the Grapes url, the model(or collection) should change to GrapeModel from OrangeModel. How to do this?
If you want a POST /Grapes to be behave differently from a POST /Oranges, you can attach your controller to both paths and evaluate the path inside your code.
const createPost = async (req, res) => {
let newPostMessage;
if (req.path === "/Oranges") newPostMessage = new OrangeModel(...);
else if (req.path === "/Grapes") newPostMessage = new GrapeModel(...);
try {
await newPostMessage.save();
...
};
app.post(["/Oranges", "/Grapes"], createPost);
Also I got the answer like this:
exports.createPost =Model=> async (req, res) => {
try {
const doc = await Model.create(req.body, {
new: true,
runValidators: true,
});
res.status(200).json({
status: 'success',
data: {
doc,
},
});
} catch (error) {
res.status(400).json({
status: 'fail',
message: error,
});
}
};
Here just call createPost function with the model name

Using promise with GraphRequestManager

Does anyone have an example on how to use promise with GraphRequestManager?
I get Cannot read property then of undefined error in my action creator.
function graphRequest(path, params, token=undefined, version=undefined, method='GET') {
return new Promise((resolve, reject) => {
new GraphRequestManager().addRequest(new GraphRequest(
path,
{
httpMethod: method,
version: version,
accessToken: token
},
(error, result) => {
if (error) {
console.log('Error fetching data: ' + error);
reject('error making request. ' + error);
} else {
console.log('Success fetching data: ');
console.log(result);
resolve(result);
}
},
)).start();
});
}
I call the above using my action creator
export function accounts() {
return dispatch => {
console.log("fetching accounts!!!!!!");
dispatch(accountsFetch());
fbAPI.accounts().then((accounts) => {
dispatch(accountsFetchSuccess(accounts));
}).catch((error) => {
dispatch(accountsFetchFailure(error));
})
}
}
I get 'Success fetching data:' in the console along with the result before the error. So the API call is made successfully. The error is after fetching the accounts in fbAPI.accounts().then((accounts) which I think is due to GraphRequestManager returning immediately instead of waiting.
I have a solution for you.
My provider look like this :
FBGraphRequest = async (fields) => {
const accessData = await AccessToken.getCurrentAccessToken();
// Create a graph request asking for user information
return new Promise((resolve, reject) => {
const infoRequest = new GraphRequest('/me', {
accessToken: accessData.accessToken,
parameters: {
fields: {
string: fields
}
}
},
(error, result) => {
if (error) {
console.log('Error fetching data: ' + error.toString());
reject(error);
} else {
resolve(result);
}
});
new GraphRequestManager().addRequest(infoRequest).start();
});
};
triggerGraphRequest = async () => {
let result = await this.FBGraphRequest('id, email');
return result;
}
That works great ! I let you adapt my solution to your system.