I can't figure where is the problem with my graphql request - node.js

I'm getting bad request code every time i try to send data query in graphql,
and I can't figure if the problem from the resolver or from the input,
below is the resolver :
const addTranslationTableAdminResolver = async (args, context, info) => {
checkAuth(context);
const videocardId = args.input.videoCardId;
const videoLink = args.input.videoLink;
const orgId = args.input.orgId;
await context.dao.createTranslationTable({
id,
orgId,
videocardId,
dateTime,
videoLink,
});
return {
statusMessage: 'SUCCESS',
};
};
and the data-object access as below:
const createTranslationTable = async ({ orgId, videocardId, videoLink }) => {
const queryString = `INSERT INTO translation_table (org_id, video_id,request_date,video_link)
VALUES ($1, $2, $3, $4) RETURNING *`;
const dateTime = new Date();
const values = [orgId, videocardId, dateTime, videoLink];
const result = await query(queryString, values);
if (result && result.rows.length === 1) {
return getAllTranslationObject(result.rows[0]);
}
};
when I'm trying to send data query i'm getting the same error as above.
const createTransaltionVideoCard = (orgId, videoCardId, videoLink) => {
return gqBackOfficeClient.mutate({
mutation: gql`
mutation {
createTranslationTable(input: {
orgId: ${orgId},
videocardId: ${videoCardId},
videoLink :"${videoLink}"
}) {
statusMessage
}
}
`,
});
};
const handleTranslationButtonClick = (orgId, videoCardId, videoLink) => {
setIsTranslationButtonClicked(true);
createTransaltionVideoCard({
orgId,
videoCardId,
videoLink,
}).then((res) => {
console.log(res);
});
};

just to update , solved this issue, it was a problem with resolvers, and now its working fine –

Related

Trouble with return statement in Node Async Await

Trying to write a query for DynamoDB and learn promises etc. The console.log(resp.Items) returns the object that I am looking for so I think my query is formatted correctly. I get a status 200 back with an empty object.
I have read up for a few days and tried to implement various changes to the code by nothing is returning the object resp.Items. I am guessing the function is returning before the const is updated with the data but I am not sure why the console.log works.
const AWS = require('aws-sdk')
const dynamodb = new AWS.DynamoDB()
const getTechs = async () => {
try {
const resp = await dynamodb
.query({
ExpressionAttributeValues: {
':tech': { S: 'TECH#' },
},
KeyConditionExpression: 'PK = :tech',
TableName: process.env.TABLE_NAME,
ScanIndexForward: true,
})
.promise()
console.log(resp.Items)
if (!resp.Items) {
return {
error: 'No Techs in the DB',
}
}
return {
tech: resp.Items,
}
} catch (error) {
console.log('Error retrieving Tech List')
console.log(error)
return {
error: 'Could not retrieve Tech List',
}
}
}
handler func
const { makeHandler } = require('./utils')
const { getTechs } = require('../data')
// const { Tech } = require('../entities')
const inputSchema = {
type: 'object',
properties: {
pathParameters: {
type: 'object',
properties: {
tech: { type: 'string' },
},
required: ['tech'],
},
},
required: ['pathParameters'],
}
const handler = async (event) => {
const { techs, error } = await getTechs()
const statusCode = error ? 500 : 200
const body = error ? JSON.stringify({ error }) : JSON.stringify({ techs })
return {
statusCode,
body,
}
}
module.exports.handler = makeHandler({ handler })
executeTransactWrite func
const executeTransactWrite = async ({ tech, params }) => {
const transactionRequest = tech.transactWriteItems(params)
let cancellationReasons
transactionRequest.on('extractError', (response) => {
try {
cancellationReasons = JSON.parse(
response.httpResponse.body.toString()
).CancellationReasons
} catch (err) {
// suppress this just in case some types of errors aren't JSON parseable
console.error('Error extracting cancellation error', err)
}
})
return new Promise((resolve, reject) => {
transactionRequest.send((err, response) => {
if (err) {
err.cancellationReasons = cancellationReasons
return reject(err)
}
return resolve(response)
})
})
}
module.exports = {
executeTransactWrite,
makehandler func
const middy = require('middy')
const {
jsonBodyParser,
validator,
httpErrorHandler,
} = require('middy/middlewares')
const makeHandler = ({ handler, inputSchema }) =>
middy(handler)
.use(jsonBodyParser())
.use(validator({ inputSchema }))
.use(httpErrorHandler())
module.exports = { makeHandler }

Node.js server gets stuck after a few API calls

I have a node.js application where I'm using the sign in functionality.
I'm facing an issue; that is, when I try to sign in, sometimes the request gets stuck. It won't return anything until I refresh the node.js server. Can anybody take a look at the code and help me out what am I doing wrong here?
Here is my Controller function
export const authenticate = async (
req: Request,
res: Response
): Promise<void> => {
try {
console.log("Login")
const result: DataObject = await model.authenticate(
req.body.username,
req.body.password
)
const { status, data } = result
res.status(status)
if(status==200) {
console.log(status)
const u : User = data as User;
const token = jwt.sign({ id: u.id }, process.env.JWT_SECRET as string)
res.json({token: token})
}
else {
res.json(data)
}
} catch (error) {
res.status(NOT_FOUND)
res.json(error)
}
}
And my Model method.
async authenticate(username: string, password: string): Promise<DataObject> {
try {
const sql =
"SELECT * FROM users WHERE username=$1"
const conn: PoolClient = await Client.connect()
const result: QueryResult<User> = await conn.query(sql, [username])
const { rows } = result
if (rows.length > 0) {
const user: User = rows[0]
const pepper: string = process.env.PASSWORD_HASH as string
const pepperedPass = password + pepper;
const validPass : boolean = bcrypt.compareSync(pepperedPass, user.password_digest);
if (validPass) {
const result: DataObject = {
status: OK,
data: user,
}
return result
}
else {
const passErr: DataObject = {
status: NOT_FOUND,
data: "Incorrect Password",
}
return passErr
}
}
const userErr: DataObject = {
status: NOT_FOUND,
data: "No User found with this Username",
}
return userErr
} catch (error) {
const userErr: DataObject = {
status: NOT_FOUND,
data: "No User found with this Username",
}
return userErr
throw new Error(`Not found, ${error}`)
}
}
I have tried res._destroy, res.set("Connection", "close"); but the issue persists.
Any suggestion/solution is appreciated.
Thank you.

I get undefined when reading my response but there is a response in React.js

I can't figure it out, the answer comes in the network table but when I want to console.log it, this will display undefined. Do you have any idea why? I attach the pictures and the code.
Here is a image with my codes and response
Here is the code - first one is where I send the response. As I said, it's going well on network tab, I get a 200 status.
export const getAccountStatus = async (req, res) => {
const user = await User.findById(req.user._id).exec();
const account = await stripe.accounts.retrieve(user.stripe_account_id);
// console.log("user account retrieve", account);
const updatedUser = await User.findByIdAndUpdate(
user._id,
{
stripe_seller: account
},
{ new: true }
)
.select("-password")
.exec();
console.log(updatedUser);
res.send(updatedUser);
};
Here is the page where i want to console.log it:
const StripeCallback = ({ history }) => {
const { auth } = useSelector(state => ({ ...state }));
const dispatch = useDispatch();
useEffect(() => {
if (auth && auth.token) accountStatus();
}, [auth]);
const accountStatus = async () => {
try {
const res = await getAccountStatus(auth.token);
console.log(res);
} catch (err) {
console.log(err);
}
};
return <div>test</div>;
};
Ang here is the Axios.post (which is working well as I know):
export const getAccountStatus = async token => {
await axios.post(
`${process.env.REACT_APP_API}/get-account-status`,
{},
{
headers: {
Authorization: `Bearer ${token}`
}
}
);
};
Thank you!
getAccountStatus doesn't have a return statement, so res in const res = await getAccountStatus(auth.token); will always be undefined.
export const getAccountStatus = async token => {
return axios.post( // <----- added return
`${process.env.REACT_APP_API}/get-account-status`,
{},
{
headers: {
Authorization: `Bearer ${token}`
}
}
);
};

Unable to access value of req.body

I am trying to do a PUT request to update my DB in Mongo using Axios so I can update the current week and season. In my route, I can access the req.body, but if I try to set the values, it says the values are undefined. I have tried many different things at this point. I ran into this issue as well: "Cast to Number failed".
Here is what the request looks like:
function currentWeek() {
const currentWeek =
"https://api.sportsdata.io/v3/nfl/scores/json/CurrentWeek?key=...";
axios.get(currentWeek).then((res) => {
const weekCheck = res.data;
const timeframeURL =
"https://api.sportsdata.io/v3/nfl/scores/json/Timeframes/current?key=...";
console.log(weekCheck);
axios.get(timeframeURL).then((res) => {
const timeframeWeek = res.data;
// console.log(timeframeWeek);
const thisWeek = timeframeWeek.filter(
(timeframeWeek) => timeframeWeek.Week === weekCheck
);
console.log(thisWeek);
const config = {
headers: {
"Content-Type": "application/json",
},
};
axios
.put("http://localhost:4000/api/currentweek/5ffce18e78d4742414cf279e", thisWeek, config)
.then((res) => console.log("working"))
.catch((err) => console.error(err));
console.log("Done!");
});
});
}
Here is my route:
router.put("/:_id", async (req, res) => {
const { Season, Week } = req.body;
const { _id } = req.params;
const weekField = {};
// SETING THE VALUES FROM REQ.BODY TO BE IN weekField
if (Season) weekField.Season = Season;
if (Week) weekField.Week = Week;
try {
let weekParam = await CurrentWeek.find({_id});
if (!weekParam) return res.stats(404).json({ msg: "ID in the Params does not exist" });
console.log(_id);
console.log(req.body) // RETURNS THE OBJECT CORRECTLY
console.log(weekField); // RETURNS AS AN EMPTY OBJECT
console.log("From Route ^^");
weekParam = await CurrentWeek.findOneAndUpdate(
_id,
{ $set: weekField },
{ new: true }
);
res.json(weekParam);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
Here is the model:
const mongoose = require('mongoose');
const CurrentWeekSchema = mongoose.Schema([{
Week: Number,
Season: Number
}]);
const CurrentWeek = module.exports = mongoose.model('currentweek', CurrentWeekSchema);
//^enables require from routes
module.exports.getCurrentWeek = function(callback, limit){
CurrentWeek.find(callback).limit(limit);
}
And here is an example of the object I am trying to take in:
[
{
SeasonType: 3,
Season: 2020,
Week: 2,
Name: 'Divisional Playoffs',
ShortName: 'Divisional',
StartDate: '2021-01-12T00:00:00',
EndDate: '2021-01-18T23:59:59',
FirstGameStart: '2021-01-16T16:35:00',
FirstGameEnd: '2021-01-16T20:35:00',
LastGameEnd: '2021-01-17T22:40:00',
HasGames: true,
HasStarted: true,
HasEnded: false,
HasFirstGameStarted: false,
HasFirstGameEnded: false,
HasLastGameEnded: false,
ApiSeason: '2020POST',
ApiWeek: '2'
}
]
I found out the issue and maybe this will be helpful for someone else in the future!
In my router file I need to change this:
const { Season, Week } = req.body;
const { _id } = req.params;
const weekField = {};
// SETING THE VALUES FROM REQ.BODY TO BE IN weekField
if (Season) weekField.Season = Season;
if (Week) weekField.Week = Week;
To this:
const data = req.body;
const { Season, Week } = data[0];
const { _id } = req.params;
const weekField = {};
// SETING THE VALUES FROM REQ.BODY TO BE IN weekField
if (Season) weekField.Season = Season;
if (Week) weekField.Week = Week;
The reason is because the data that the put request is receiving is coming in an array, so I had to set the req.body to the first object in the array.

How to call external function in jest

I'm New to unit test and trying to test my controller method.my project architecture design is as follow
Controller->Service->Model.
My test scenarios :
Pass correct parameters to controller method and test success response
Pass Invalid parameters to controller method and test error response
When i going to test scenario 1 ,according to my understanding i want to mock my programService and it return values.I have write test as follow and got errors.
I would really appreciate some one can fix this
ProgramsController.js
const ProgramService = require('../../services/program/programService');
class ProgramsController {
constructor() {
this.programService = new ProgramService();
}
async subscribe(req, res) {
try {
const { userId, uuid, msisdn, body: { programId } } = req;
const data = { userId, programId, msisdn, uuid }
const subscribe = await this.programService.subscribeUser(data);
res.json({
status: true,
message: 'Success',
friendly_message: constant.MSG.SUBSCRIPTION,
data: subscribe
})
} catch (error) {
res.status(500)
.json({
status: false,
message: 'Fail',
friendly_message: constant.MSG.SUBSCRIPTION_FAIL
})
}
}
}
ProgramService.js
class ProgramService {
constructor() {
this.subscriber = new Subscriber();
this.subsciberProgram = new SubsciberProgram()
}
async subscribeUser(data) {
try {
const { msisdn, userId, programId, uuid } = data;
...
return subscribedData;
} catch (error) {
throw error;
}
}
}
module.exports = ProgramService;
test.spec.js
const ProgramsService = require('../src/services/program/programService')
const ProgramsController = require('../src/controllers/programs/programsController')
const programController = new ProgramsController()
const programsService = new ProgramsService()
beforeAll(() => {
db.sequelize.sync({ force: true }).then(() => { });
});
const mockRequest = (userId, uuid, msisdn, body) => ({
userId,
uuid,
msisdn,
body,
});
const mockResponse = () => {
const res = {};
res.status = jest.fn().mockReturnValue(res);
res.json = jest.fn().mockReturnValue(res);
return res;
};
const serviceRecord = { userId: 1, programId: 1, msisdn: '56768382967', uuid: '46651a19-3ef1-4149-818e-9bd8a5f359ef' };
const fakeServiceReturn = { program_id: 1, amount: 5, no_of_questions: 10 }
describe('Subscribe', () => {
test('should return 200', async () => {
const req = mockRequest(
1,
'56768382967',
'46651a19-3ef1-4149-818e-9bd8a5f359ef',
{ 'programId': 1 }
);
const res = mockResponse();
const spy = jest.spyOn(programsService, 'subscribeUser').mockImplementation(() => serviceRecord);
await programController.subscribe(req, res);
expect(programsService.subscribeUser()).toHaveBeenCalledWith(fakeServiceReturn);
expect(res.status).toHaveBeenCalledWith(500);
expect(res.json).toHaveBeenCalledWith({
status: true,
message: 'Success',
friendly_message: 'successfull get data',
data : { program_id: 1, amount: 5, no_of_questions: 10 }
});
spy.mockRestore();
});
});
how can i mock programService.subscribeUser and test success response?
This mock should return a promise:
jest.spyOn(programsService, 'subscribeUser').mockImplementation(() => Promise.resolve(serviceRecord));

Resources