I'm trying to send a post request, take the request details and turn it into a PDF document using ejs - pdf

TypeError: val.slice is not a function at escapeString (C:\blackops yonatan nasimov\node_angular_sql\backend\node_modules\sqlstring\lib\SqlString.js:202:23) at Object.escape (C:\blackops yonatan nasimov\node_angular_sql\backend\node_modules\sqlstring\lib\SqlString.js:56:21) at Object.arrayToList (C:\blackops yonatan nasimov\node_angular_sql\backend\node_modules\sqlstring\lib\SqlString.js:69:48) at Object.escape (C:\blackops yonatan nasimov\node_angular_sql\backend\node_modules\sqlstring\lib\SqlString.js:46:26) at Object.format (C:\blackops yonatan nasimov\node_angular_sql\backend\node_modules\sqlstring\lib\SqlString.js:100:19) at Connection.format (C:\blackops yonatan nasimov\node_angular_sql\backend\node_modules\mysql\lib\Connection.js:271:20) at Connection.query (C:\blackops yonatan nasimov\node_angular_sql\backend\node_modules\mysql\lib\Connection.js:189:22) at generateReport (C:\blackops yonatan nasimov\node_angular_sql\backend\controllers\billControler.js:20:12) at Layer.handle [as handle_request] (C:\blackops yonatan nasimov\node_angular_sql\backend\node_modules\express\lib\router\layer.js:95:5) at next (C:\blackops yonatan nasimov\node_angular_sql\backend\node_modules\express\lib\router\route.js:144:13)
generateReport: (req, res) => {
const generatedUuid = uuid.v1;
const orderDetails = req.body;
const q = "INSERT INTO `cafemanger`.`bills` (`uuid`, `name`, `email`, `contectNumber`, `paymentMethod`, `total`, `productDetails`, `createdBy`) VALUES (?);";
const values = [
generatedUuid, orderDetails.name, orderDetails.email, orderDetails.contectNumber, orderDetails.paymentMethod, orderDetails.total, orderDetails.productDetails, orderDetails.createdBy,
];
db.query(q, [values], (err, data) => {
if (err) return res.status(500).json(err);
ejs.renderFile(path.join(__dirname, '', "report.ejs"), {
productDetails: orderDetails.productDetails,
name: orderDetails.name,
email: orderDetails.email,
contectNumber: orderDetails.contectNumber,
paymentMethod: orderDetails.paymentMethod,
totalAmount: orderDetails.total
}, (err, result) => {
if (err) {
return res.status(500).json(err);
} else {
pdf.create(result).toFile('../generated_pdf/' + generatedUuid + '.pdf', function (err, pdfData) {
if (err) {
console.log(err);
return res.status(500).json(err);
} else {
return res.status(200).json({ uuid: generatedUuid });
}
})
}
})
});
}

Related

Cannot set Header after already being sent // node express

I am prompted with cannot set headers after they are already being set.
My code intercept for put method sent on the URL it then checks for missing id, after that checks if no field inputted is undefined it then perform try-catch method within which it updates for given id. If the id is not correct then it responds with an error.
My code is :
.put(async function (req, res){
console.log(req.body._id + " is id.")
const {_id, issue_title, issue_text, created_by, assigned_to, status_text, open} = req.body;
if(!_id){
res.json({error: "missing _id"})
}
const fields = {issue_title, issue_text, created_by, assigned_to, status_text, open}
const checkAllUndefined = Object.values(fields).every(val => (val == undefined || val == '')? true: false)
if(checkAllUndefined){
res.json({ error: 'no update field(s) sent', _id})
} else{
try{
await db.findOneAndUpdate({_id: new mongodb.ObjectID(_id)}, {$set:
{issue_title,issue_text,created_by, assigned_to, status_text, open,
updated_on: new Date()}}, {
new: true,
omitUndefined: true
})
res.json({ result: 'successfully updated', _id})
}catch(err){
res.json({ error: 'could not update', _id})
}
}
})
Your first If statement is returning the response if _id is undefined !
if(!_id){
res.json({error: "missing _id"})
}
After sending this response your next if block or its else block gets executed
which leads to sending another response which is not possible or allowed !, You have to nest if else block like this
put(async function (req, res) {
console.log(req.body._id + " is id.")
const {_id, issue_title, issue_text, created_by, assigned_to, status_text, open} = req.body;
if (!_id) {
res.json({error: "missing _id"})
} else {
if (checkAllUndefined) {
res.json({error: 'no update field(s) sent', _id})
} else {
try {
await db.findOneAndUpdate({_id: new mongodb.ObjectID(_id)}, {
$set:
{
issue_title, issue_text, created_by, assigned_to, status_text, open,
updated_on: new Date()
}
}, {
new: true,
omitUndefined: true
})
res.json({result: 'successfully updated', _id})
} catch (err) {
res.json({error: 'could not update', _id})
}
}
}
)
}
by doing this you are only sending response only once.

Vue js - not all the data showing after store dispatch

The select box not showing sometimes the first color and sometimes not showing the first color.
How can i make it to show all the item in the select box?
I'm not getting for some reason all the promises
You can see the issue in the picture
Please help me to fix this issue i'm new to vue js
My code:
data() {
return {
propertiesTree: []
}
}
getPropertyGroups(objectId: number): void {
if (this.$data.currentObjectId === objectId)
return;
let component: any = this;
this.$data.currentObjectId = objectId;
component.showLoader();
this.$store.dispatch('properties/getPropertyGroups', objectId)
.then(({ data, status }: { data: string | Array<propertiesInterfaces.PropertyGroupDto>, status: number }) => {
// console.log(data, "data");
// console.log(status, "status")
if (status === 500) {
this.$message({
message: data as string,
type: "error"
});
}
else {
let anyData = data as any;
anyData.map(item => {
item.properties.map(prop => {
if(prop.type.toString() === 'dictionary'){
prop.dictionaryList = [];
prop.color = '';
this.getWholeDictionaryList(prop.dictionaryId.value, prop)
}
});
});
}
component.hideLoader();
});
},
getWholeDictionaryList(dictionaryId: number, prop: any){
this.$store.dispatch('dictionaries/getWholeDictionaryList', dictionaryId).then(
({ data, status }: { data: Array<any> |string , status: number }) => {
if (status === 500) {
this.$message({
message: data as string,
type: "error"
});
} else {
const arrData = data as Array<any>;
arrData.map((item,index) => {
prop.dictionaryList = [];
prop.dictionaryList = data;
this.getDictionaryItemColor(item.id.value, data, index, prop);
});
}
});
},
getDictionaryItemColor(dictionaryItemId:number, dictionaryList: Array<any>, index:number, current){
this.$store.dispatch('patterns/getDictionaryItemColor', dictionaryItemId).then((data: any, status: number) => {
if (status === 500) {
this.$message({
message: data as string,
type: "error"
});
} else{
debugger
if(current.dictionaryItemId.value === data.data.sceneObjectId)
current.color = data.data.colorString;
dictionaryList[index].color = data.data.colorString ? data.data.colorString: '#FFFFFF';
}
});
},
Html code of the select box
<el-select v-model="data.color" placeholder="Select">
<el-option
v-for="item in data.dictionaryList"
:key="item.name"
:label="item.color"
:value="item.color">
</el-option>
</el-select>
I did return to dispatch
let dispatch = this.getWholeDictionaryList(prop.dictionaryId.value, prop)
let promiseArr = [];
promiseArr.push(dispatch);
after the map closing tag i did
Promise.all(promisArr).then( () => {
debugger
this.$data.propertiesTree = anyData;
});
And I've got it solved

TypeError: response.data is undefined

I'm having problems with promise response for a vForm PUT to UPDATE a model (backend in laravel).
The response code is 200 (OK, updated) and the model is updated, but I don't know why I'm having error with "response.data" in catch. There is no error and code in ".then()" is running correctly.
EDIT
Service Update funciton (vue) using vForm.
updateService(){
this.$Progress.start();
this.service.put('api/service/' + this.service.id)
.then( function (response) {
Toast.fire({
type: 'success',
title: response.data['Response']
});
this.$Progress.finish();
})
.catch( function (response) {
console.log(response);
Swal.fire("Error!", response.data['Response'], "warning");
this.$Progress.fail();
});
this.$events.$emit('ServiceInform');
},
Function in backend (laravel).
public function update(Request $request, Service $service)
{
$this->validate($request, [
'id_customers' => 'required|int',
'date' => 'required|date',
'id_technicians' => 'required|int',
'location' => 'required|string',
'details' => 'required|string'
]);
if ($request['id_technicians'] !== $service['id_technicians']) {
$assignated_by = Auth::user()->id;
$assigned_date = date('Y-m-d H:i:s');
} else {
$assignated_by = $service['assignated_by'];
$assigned_date = $service['assigned_date'];
}
if ($request['id_technicians'] == 0) {
$state = 'P';
} else {
$state = 'I';
}
$service->date = $request['date'];
$service->id_technicians = $request['id_technicians'];
$service->location = $request['location'];
$service->details = $request['details'];
$service->assigned_date = $assigned_date;
$service->assigned_by = $assignated_by;
$service->state = $state;
try {
$service->save();
return Response::json([
'Response' => 'Servicio actualizado.'
], 201);
} catch (Exception $e) {
return Response::json([
'Response' => 'No se actualizó el servicio.'
], 422);
}
}
This line looks problematic to me:
this.$Progress.finish();
It's trying to access this within the function passed to then. It seems unlikely that this will be referencing what you're expecting. You should be able to confirm with suitable console logging. My suspicion is that attempting to call this.$Progress.finish() will throw an error, triggering the catch.
Try using arrow functions for your then and catch callbacks instead.

I am getting this error ,"value for message cannot be cast from double to string"

I am getting this error when I am trying pass object to axios method "value for message cannot be cast from double to string". Does any one have Idea about this.
I have added my two functions.
addNotes = (formData) => {
let noteText = ''
Object.keys(formData).map((item) => {
noteText += formData[item] !== undefined ? `${formData[item]} \n` : ``
})
let localLocation = `${this.state.localAddress.locality}, ${this.state.localAddress.subLocality}`
let { userMetaData, graphListlimit, graphListoffset, imdCode } = this.state
let obj = {
'edEmployeeCode': userMetaData.ed_employee_code,
'edName': userMetaData.ed_name,
'edRoleCode': userMetaData.ed_role_code,
'imdCode': imdCode,
'imdSegment': null,
'bnNoteText': noteText,
'location': localLocation,
'meetingType': this.state.meetingType
}
this.props.onAddNotesAction(obj)
}
export const addNotesAction = (obj) => {
let params = {
ed_employee_code: obj.empCode,
ed_role_code: obj.empRoleCode,
ed_channel: obj.empChannel,
ed_name: obj.edName,
imd_code: obj.imdCode,
imd_segment: null,
bn_note_text: obj.bnNoteText,
location: obj.location,
meeting_type: obj.meetingType
}
return dispatch => {
axios.defaults.headers.common['Authorization'] = obj.token;
axios.post(`${Config.apiRootPath}/meetings/addbranchnote`,
params,
).then(response => {
dispatch(addNotesSuccess(response));
}).catch(err => {
dispatch(addNotesFailure(err.response));
});
};
};

How to unit test API calls with axios() in react-native with Jest

I am developing Sample Application in React-native . I used Jest to use unit testing, i don't have an idea about Jest Api call
I want to need without using Promises:
Here this is my Code:
this is My Function Code:
/**
* #description Action to call nilpick service ,on success increment route as well as mark the location as fulfilled
*/
function nilPick() {
return async (dispatch, getState) => {
const currentState = getState();
const { user, picking } = currentState;
const { currentRouteIndex, pickRoute } = getState().picking.pickRouteInfo;
const { workId } = picking.pickWorkInfo;
const nilPickItem = pickRoute[currentRouteIndex];
const currentItem = getCurrentItem(currentState);
const currentTime = dateFunctions.getCurrentUTC();
const nilpickedItem = [
{
orderId: nilPickItem.fulfillOrdNbr,
lineNbr: nilPickItem.ordLine,
pickUpcNbr: nilPickItem.upc,
pickDisplayTs: currentTime,
pickUom: currentItem.workDetail.uom,
pickedLoc: nilPickItem.location,
locationType: nilPickItem.locType,
locId: nilPickItem.locId,
pickByType: currentItem.workDetail.pickByType,
exceptionPick: false,
gtinPrefRankNbr: 0,
pickUpcTypeCd: 5100
}
];
const { status, statusText } = await pickingService.nilPick(nilpickedItem, user, workId);
if (status === 200 || statusText === 'Created') {
console.info('Item nilpicked');
if (currentRouteIndex < pickRoute.length) {
dispatch(incrementRoute());
} else {
Alert.alert(
'Nilpick Complete',
[
{
text: 'OK',
onPress: () => {
dispatch(endPicking());
}
}
],
{ cancelable: false }
);
console.log('End of pickwalk');
return;
}
} else {
console.info('error in nilpicking item ');
}
};
}
This is my code above method to Converting Like this below sample test Case:
This is sample Test i want to call Api How to implement in Jest
it('Test For nillPic', () => {
const initialState = {
picking: {
pickRouteInfo: {
"fulfillOrdNbr": pickRouteInfo.fulfillOrdNbr,
"orderLine": '1',
"upc": '4155405089',
"location": 'A-1-1',
"availableLocsToPick": '2',
'suggSubPendingPicks?': 'N',
'manualSubPendingPicks?': 'N',
"lineFullfilled": 'false',
"currentRouteIndex": 1,
"pickRoute": ['r1', 'r2', 'r3']
}
}
};
// console.log("state data...", initialState);
const store = mockStore(initialState);
store.dispatch(actions.pickRouteActions.nilPickSuccess());
const expectedAction = [{ type: 'INCREMENT_ROUTE' }];
const localActions = store.getActions();
expect(localActions).toEqual(expectedAction);
});
Finally This is my code Please . Thanks in Advance