I'm building a profile page for users of my app (nextjs 12) and when I add authentication middleware it works fine locally but when deployed to the production server (apache shared hosting with nodejs v 14 installed) it throws error 500
my node version installed locally is v16.16.0 could that affect this issue?
any suggestions?
profile.tsx:
const ProfileEditor = () => {
const dispatch = useDispatch();
const {
profile,
profileLogin,
user
} = useSelector((state: RootState) => state.Auth);
useEffect(() => {
dispatch(FetchProfileAsync());
}, []);
const [preview, setPreview] = useState < string > ();
const handleFormSubmit = async(values: any, e: any) => {
dispatch(UpdateProfileAsync(values as any));
};
let initialValues = {
image: profile ? .image ? .full_path,
first_name: profile ? .first_name,
last_name: profile ? .last_name,
email: profile ? .email,
phone: profile ? .phone,
};
const FILE_SIZE = 160 * 1024;
const SUPPORTED_FORMATS = ['image/jpg', 'image/png'];
const checkoutSchema = yup.object().shape({
image: yup.mixed().required('A file is required'),
// .test('fileSize', 'File too large', (value) => value && value.size <= FILE_SIZE)
// .test('fileFormat', 'Unsupported Format', (value) => value && SUPPORTED_FORMATS.includes(value.type)),
first_name: yup.string().required('required'),
last_name: yup.string().required('required'),
email: yup.string().email('invalid email').required('required'),
phone: yup.string().required('required'),
});
return ( <
CustomerDashboardLayout >
<
DashboardPageHeader icon = {
Person
}
title = 'Edit Profile'
navigation = { < CustomerDashboardNavigation / >
}
/>
<
Card1 >
<
Formik enableReinitialize initialValues = {
initialValues
}
validationSchema = {
checkoutSchema
}
onSubmit = {
(values: any, e: any) => handleFormSubmit(values, e)
} >
{
({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
setFieldValue
}) => ( <
form onSubmit = {
handleSubmit
} >
<
FlexBox alignItems = 'flex-end'
mb = {
3
} >
<
Avatar src = {
preview ? ? user ? .image ? .full_path
}
sx = {
{
height: 64,
width: 64
}
}
alt = 'user image' / >
{ /* <img src={user?.image?.full_path} height={100} width={100} alt='fdss' /> */ }
<
Box ml = {-2.5
} >
<
label htmlFor = 'profile-image' >
<
Button component = 'span'
color = 'secondary'
sx = {
{
bgcolor: 'grey.300',
height: 'auto',
p: '8px',
borderRadius: '50%',
}
} >
<
CameraEnhance fontSize = 'small' / >
<
/Button> <
/label> <
/Box> <
Box display = 'none' >
<
input name = 'image'
onChange = {
(newFile: any) => {
setFieldValue('image', newFile.currentTarget.files[0]);
FileToBase64(newFile.currentTarget.files[0] as any).then((res) => setPreview(res));
}
}
id = 'profile-image'
accept = 'image/*'
type = 'file' /
>
<
/Box> <
/FlexBox>
<
Box mb = {
4
} >
<
Grid container spacing = {
3
} >
<
Grid item md = {
6
}
xs = {
12
} >
<
ETextField mb = {
1.5
}
name = 'first_name'
label = 'First Name'
placeholder = 'First Name'
variant = 'outlined'
size = 'small'
fullWidth onBlur = {
handleBlur
}
onChange = {
handleChange
}
value = {
values.first_name || ''
}
error = {!!touched.first_name && !!errors.first_name
}
helperText = {
touched.first_name && errors.first_name
}
/> <
/Grid> <
Grid item md = {
6
}
xs = {
12
} >
<
ETextField mb = {
1.5
}
name = 'last_name'
label = 'Last Name'
placeholder = 'Last Name'
variant = 'outlined'
size = 'small'
fullWidth onBlur = {
handleBlur
}
onChange = {
handleChange
}
value = {
values.last_name || ''
}
error = {!!touched.last_name && !!errors.last_name
}
helperText = {
touched.last_name && errors.last_name
}
/> <
/Grid> <
Grid item md = {
6
}
xs = {
12
} >
<
ETextField mb = {
1.5
}
name = 'email'
label = 'Email'
placeholder = 'exmple#mail.com'
variant = 'outlined'
size = 'small'
type = 'email'
fullWidth onBlur = {
handleBlur
}
onChange = {
handleChange
}
value = {
values.email || ''
}
error = {!!touched.email && !!errors.email
}
helperText = {
touched.email && errors.email
}
/> <
/Grid> <
Grid item md = {
6
}
xs = {
12
} >
<
ETextField mb = {
1.5
}
name = 'phone'
label = 'Phone'
placeholder = '09********'
variant = 'outlined'
size = 'small'
fullWidth onBlur = {
handleBlur
}
onChange = {
handleChange
}
value = {
values.phone || ''
}
error = {!!touched.phone && !!errors.phone
}
helperText = {
touched.phone && errors.phone
}
/> <
/Grid> <
/Grid> <
/Box>
<
ELoadingButton type = 'submit'
variant = 'contained'
loading = {
profileLogin === 'loading'
}
buttonText = 'Save Changes'
loadingPosition = 'start'
fullWidth = {
true
}
color = 'primary' /
>
<
/form>
)
} <
/Formik> <
/Card1> <
/CustomerDashboardLayout>
);
};
export default ProfileEditor;
middlware.tsx
// eslint-disable-next-line #next/next/no-server-import-in-page
import { NextResponse } from 'next/server';
// eslint-disable-next-line #next/next/no-server-import-in-page
import type { NextRequest } from 'next/server';
import { KEY_TOKEN_COOKIE } from 'src/constants';
const middleware = (request: NextRequest, response: NextResponse) => {
const token = request?.cookies[KEY_TOKEN_COOKIE];
if (!token) return NextResponse.rewrite(new URL('/error/auth', request.url));
};
export default middleware;
I'm trying to generate more than one thousand pdf files using surveyPDF.
The problem is that i can generate only 80 pdf files...
I'm passing an array with more than 1000 pdf to generate.
Code :
query.map(async items => {
const { generatePdf } = await import("~/lib/survey");
const filename = kebabCase(
`${campaign.title} - ${items.employee.fullName.toLowerCase()} -${moment().format("DD/MM/YYYY - HH:mm")} `
);
return generatePdf(campaign.template.body, items, filename, 210, 297);
});
The code which generate each pdfs :
import autoTable from "jspdf-autotable";
import { SurveyPDF, CommentBrick, CompositeBrick, PdfBrick, TextBrick } from "survey-pdf";
import { format } from "~/utils/date";
class AutoTableBrick extends PdfBrick {
constructor(question, controller, rect, options) {
super(question, controller, rect);
this.margins = {
top: controller.margins.top,
bottom: controller.margins.bot,
right: 30,
left: 30,
};
this.options = options;
}
renderInteractive() {
if (this.controller.doc.lastAutoTable && !this.options.isFirstQuestion) {
this.options.startY = this.yTop;
}
autoTable(this.controller.doc, {
head: [
[
{
content: this.question.title,
colSpan: 2,
styles: { fillColor: "#5b9bd5" },
},
],
],
margin: { ...this.margins },
styles: { fillColor: "#fff", lineWidth: 1, lineColor: "#5b9bd5", minCellWidth: 190 },
alternateRowStyles: { fillColor: "#bdd6ee" },
...this.options,
});
}
}
export async function generatePdf(json, data, filename, pdfWidth, pdfHeight) {
if (!json) {
return Promise.reject("Invalid json for pdf export");
}
for (const page of json.pages) {
page.readOnly = true;
}
const surveyPDF = new SurveyPDF(json, {
fontSize: 11,
format: [pdfWidth, pdfHeight],
commercial: true,
textFieldRenderAs: "multiLine",
});
surveyPDF.showQuestionNumbers = "off";
surveyPDF.storeOthersAsComment = false;
//TODO This does not work well with dynamic dropdown, bug declared
// surveyPDF.mode = "display";
surveyPDF.mergeData({ ...data, _: {} });
surveyPDF.onRenderQuestion.add(function(survey, options) {
const { bricks, question } = options;
if (question.getType() === "comment" && question.value && bricks.length > 0) {
for (const brick of bricks) {
if (brick.value) {
brick.value = question.value.replace(/\t/g, " ");
}
if (brick instanceof CompositeBrick) {
const { bricks } = brick;
for (const brick of bricks) {
if (brick instanceof CommentBrick) {
brick.value = question.value.replace(/\t/g, " ");
}
}
}
}
}
});
surveyPDF.onRenderQuestion.add(async function(survey, options) {
const {
point,
bricks,
question,
controller,
module: { SurveyHelper },
} = options;
if (question.getType() === "multipletext") {
const body = [];
let extraRows = 0;
let rows = question.getRows();
for (let i = 0; i < rows.length; i++) {
for (let j = 0; j < rows[i].length; j++) {
let { title, value, inputType } = rows[i][j];
if (inputType === "date") {
value = format(value);
}
if (typeof value === "string" && value.length > 0) {
const valueEstRows = value.match(/.{1,70}/g).length;
if (valueEstRows > 1) {
extraRows += valueEstRows;
}
}
body.push([title, value || "N/A"]);
}
}
//TODO Use SurveyHelper helperDoc do calculate the height of the auto table
const startY = point.yTop;
const height = 21.5 * (body.length + 1) + 8.5 * extraRows;
const isFirstQuestion = question.title === question.parent.questions[0].title;
options.bricks = [
new AutoTableBrick(question, controller, SurveyHelper.createRect(point, bricks[0].width, height), {
startY,
body,
isFirstQuestion,
}),
];
}
});
surveyPDF.onRenderQuestion.add(async function(survey, options) {
const {
point,
question,
controller,
module: { SurveyHelper },
} = options;
if (question.getType() === "text") {
//Draw question background
const { default: backImage } = await import("~/public/assets/images/block.png");
const backWidth = SurveyHelper.getPageAvailableWidth(controller);
const backHeight = SurveyHelper.pxToPt(100);
const imageBackBrick = SurveyHelper.createImageFlat(point, null, controller, backImage, backWidth, backHeight);
options.bricks = [imageBackBrick];
point.xLeft += controller.unitWidth;
point.yTop += controller.unitHeight;
const oldFontSize = controller.fontSize;
const titleBrick = await SurveyHelper.createTitleFlat(point, question, controller);
controller.fontSize = oldFontSize;
titleBrick.unfold()[0]["textColor"] = "#6a6772";
options.bricks.push(titleBrick);
//Draw text question text field border
let { default: textFieldImage } = await import("~/public/assets/images/input.png");
let textFieldPoint = SurveyHelper.createPoint(imageBackBrick);
textFieldPoint.xLeft += controller.unitWidth;
textFieldPoint.yTop -= controller.unitHeight * 3.3;
let textFieldWidth = imageBackBrick.width - controller.unitWidth * 2;
let textFieldHeight = controller.unitHeight * 2;
let imageTextFieldBrick = SurveyHelper.createImageFlat(
textFieldPoint,
null,
controller,
textFieldImage,
textFieldWidth,
textFieldHeight
);
options.bricks.push(imageTextFieldBrick);
textFieldPoint.xLeft += controller.unitWidth / 2;
textFieldPoint.yTop += controller.unitHeight / 2;
let textFieldValue = question.value || "";
if (textFieldValue.length > 90) {
textFieldValue = textFieldValue.substring(0, 95) + "...";
}
const textFieldBrick = await SurveyHelper.createBoldTextFlat(
textFieldPoint,
question,
controller,
textFieldValue
);
controller.fontSize = oldFontSize;
textFieldBrick.unfold()[0]["textColor"] = "#EFF8FF";
options.bricks.push(textFieldBrick);
}
});
surveyPDF.onRenderQuestion.add(async function(survey, options) {
const {
point,
question,
controller,
module: { SurveyHelper },
} = options;
if (question.getType() === "radiogroup" || question.getType() === "rating") {
options.bricks = [];
const oldFontSize = controller.fontSize;
const titleLocation = question.hasTitle ? question.getTitleLocation() : "hidden";
let fieldPoint;
if (["hidden", "matrix"].includes(titleLocation)) {
fieldPoint = SurveyHelper.clone(point);
} else {
const titleBrick = await SurveyHelper.createTitleFlat(point, question, controller);
titleBrick.xLeft += controller.unitWidth;
titleBrick.yTop += controller.unitHeight * 2;
controller.fontSize = oldFontSize;
titleBrick.unfold()[0]["textColor"] = "#6a6772";
options.bricks.push(titleBrick);
fieldPoint = SurveyHelper.createPoint(titleBrick);
fieldPoint.yTop += controller.unitHeight * 1.3;
}
//Draw checkbox question items field
const { default: itemEmptyImage } = await import("~/public/assets/images/unchecked.png");
const { default: itemFilledImage } = await import("~/public/assets/images/checked.png");
const itemSide = controller.unitWidth;
let imageItemBrick;
const choices = question.getType() === "rating" ? question.visibleRateValues : question.visibleChoices;
for (const choice of choices) {
const isItemSelected =
question.getType() === "rating" ? question.value === choice.value : choice === question.selectedItem;
imageItemBrick = SurveyHelper.createImageFlat(
fieldPoint,
null,
controller,
isItemSelected ? itemFilledImage : itemEmptyImage,
itemSide,
itemSide
);
options.bricks.push(imageItemBrick);
const textPoint = SurveyHelper.clone(fieldPoint);
textPoint.xLeft += itemSide + controller.unitWidth / 2;
textPoint.yTop += itemSide / 12;
const itemValue = choice.locText.renderedHtml;
const checkboxTextBrick = await SurveyHelper.createTextFlat(
textPoint,
question,
controller,
itemValue,
TextBrick
);
checkboxTextBrick.unfold()[0]["textColor"] = "#6a6772";
fieldPoint.yTop = imageItemBrick.yBot + SurveyHelper.GAP_BETWEEN_ROWS * controller.unitHeight;
options.bricks.push(checkboxTextBrick);
}
}
});
surveyPDF.onRenderFooter.add(function(survey, canvas) {
canvas.drawText({
text: canvas.pageNumber + "/" + canvas.countPages,
fontSize: 10,
horizontalAlign: "right",
margins: {
right: 12,
},
});
});
return await surveyPDF.raw(`./pdf/${filename}.pdf`);
}
The error :
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
I have already try to increase the node memory using $env:NODE_OPTIONS="--max-old-space-size=8192"
(I use terraform 0.12.20)
I have the following snippet in my code:
locals {
x = merge(values({
for location in local.locations: location => {
for apsvc_name in var.apsvc_names: "${location}-${apsvc_name}" => {
location = location
apsvc_name = apsvc_name
}
}
})...)
The x local is then output. Applying the configuration results in:
Error: Invalid expanding argument value
on ..\..\hosting-modules\web\app_hosting.tf line 35, in locals:
35: x = merge(values({
36: for location in local.locations: location => {
37: for apsvc_name in var.apsvc_names: "${location}-${apsvc_name}" => {
38: location = location
39: apsvc_name = apsvc_name
40: }
41: }
42: })...)
The expanding argument (indicated by ...) must be of a tuple, list, or set
type.
Now if I strip the call to merge(...) and assign the result of values to x, the result is output just fine:
x = [
{
"centralus-backoffice" = {
"apsvc_name" = "backoffice"
"location" = "centralus"
}
"centralus-gateway" = {
"apsvc_name" = "gateway"
"location" = "centralus"
}
"centralus-javascriptclient" = {
"apsvc_name" = "javascriptclient"
"location" = "centralus"
}
},
{
"eastus2-backoffice" = {
"apsvc_name" = "backoffice"
"location" = "eastus2"
}
"eastus2-gateway" = {
"apsvc_name" = "gateway"
"location" = "eastus2"
}
"eastus2-javascriptclient" = {
"apsvc_name" = "javascriptclient"
"location" = "eastus2"
}
},
]
And it is clearly a list, so it should qualify for ... just fine.
What am I missing?
EDIT 1
Replacing locations with a compile time list works:
locals {
locations = ["abc", "xyz"]
x = merge(values({
for location in local.locations: location => {
for apsvc_name in var.apsvc_names: "${location}-${apsvc_name}" => {
location = location
apsvc_name = apsvc_name
}
}
})...)
}
Which results in:
Outputs:
x = {
"abc-backoffice" = {
"apsvc_name" = "backoffice"
"location" = "abc"
}
"abc-gateway" = {
"apsvc_name" = "gateway"
"location" = "abc"
}
"abc-javascriptclient" = {
"apsvc_name" = "javascriptclient"
"location" = "abc"
}
"xyz-backoffice" = {
"apsvc_name" = "backoffice"
"location" = "xyz"
}
"xyz-gateway" = {
"apsvc_name" = "gateway"
"location" = "xyz"
}
"xyz-javascriptclient" = {
"apsvc_name" = "javascriptclient"
"location" = "xyz"
}
}
But replace "abc" with a variable value and it stops working:
locals {
locations = [var.primary_location, "xyz"]
x = merge(values({
for location in local.locations: location => {
for apsvc_name in var.apsvc_names: "${location}-${apsvc_name}" => {
location = location
apsvc_name = apsvc_name
}
}
})...)
}
And bang:
Error: Invalid expanding argument value
on ..\..\hosting-modules\web\app_hosting.tf line 5, in locals:
5: x = merge(values({
6: for location in local.locations: location => {
7: for apsvc_name in var.apsvc_names: "${location}-${apsvc_name}" => {
8: location = location
9: apsvc_name = apsvc_name
10: }
11: }
12: })...)
|----------------
| local.locations is tuple with 2 elements
The expanding argument (indicated by ...) must be of a tuple, list, or set
type.
EDIT 2
So, the code that should work (I improved it - values is not needed):
merge([
for location in local.locations: {
for apsvc_name in var.apsvc_names: "${location}-${apsvc_name}" => {
location = location
apsvc_name = apsvc_name
}
}
]...)
does not work for mysterious reasons. I ended up with the following workaround:
_y1 = [
for location in local.locations: {
for apsvc_name in var.apsvc_names: "${location}-${apsvc_name}" => {
location = location
apsvc_name = apsvc_name
}
}
]
_y2 = flatten([for m in local._y1: [for k,v in m: {
key = k
value = v
}]])
x = zipmap(local._y2.*.key, local._y2.*.value)
That one does work.
EDIT 3
https://github.com/hashicorp/terraform/issues/24033
I have been working on a project to generate configurable dashboards.
so i have to generate schema dynamically based on an api request. is there any way to do that?
it will be very helpful if there is any working example!
There's an asyncModule function for this scenario. You can check example below:
const fetch = require('node-fetch');
const Funnels = require('Funnels');
asyncModule(async () => {
const funnels = await (await fetch('http://your-api-endpoint/funnels')).json();
class Funnel {
constructor({ title, steps }) {
this.title = title;
this.steps = steps;
}
get transformedSteps() {
return Object.keys(this.steps).map((key, index) => {
const value = this.steps[key];
let where = null
if (value[0] === PAGE_VIEW_EVENT) {
if (value.length === 1) {
where = `event = '${value[0]}'`
} else {
where = `event = '${value[0]}' AND page_title = '${value[1]}'`
}
} else {
where = `event = 'se' AND se_category = '${value[0]}' AND se_action = '${value[1]}'`
}
return {
name: key,
eventsView: {
sql: () => `select * from (${eventsSQl}) WHERE ${where}`
},
timeToConvert: index > 0 ? '30 day' : null
}
});
}
get config() {
return {
userId: {
sql: () => `user_id`
},
time: {
sql: () => `time`
},
steps: this.transformedSteps
}
}
}
funnels.forEach((funnel) => {
const funnelObject = new Funnel(funnel);
cube(funnelObject.title, {
extends: Funnels.eventFunnel(funnelObject.config),
preAggregations: {
main: {
type: `originalSql`,
}
}
});
});
})
More info: https://cube.dev/docs/schema-execution-environment#async-module
Invalid shipping method in magento 1.8.1?
When my cart value in 950 - 999 INR but below 950 or above 999 working fine?
One page controller code is below.
Kindly help me
onePageController.php
<?php
require_once Mage::getModuleDir('controllers', 'Mage_Checkout').DS.'OnepageController.php';
class Webly_QuickCheckout_OnepageController extends Mage_Checkout_OnepageController
{
public function saveBillingAction()
{
if ($this->_expireAjax()) {
return;
}
if ($this->getRequest()->isPost()) {
// $postData = $this->getRequest()->getPost('billing', array());
// $data = $this->_filterPostData($postData);
$data = $this->getRequest()->getPost('billing', array());
$customerAddressId = $this->getRequest()->getPost('billing_address_id', false);
if (isset($data['email'])) {
$data['email'] = trim($data['email']);
}
$data['use_for_shipping'] = 1;
$result = $this->getOnepage()->saveBilling($data, $customerAddressId);
if (!isset($result['error'])) {
if (!isset($result['error'])) {
if ($this->getOnepage()->getQuote()->isVirtual()) {
$result['goto_section'] = 'payment';
$result['update_section'] = array(
'name' => 'payment-method',
'html' => $this->_getPaymentMethodsHtml()
);
} elseif (isset($data['use_for_shipping']) && $data['use_for_shipping'] == 1) {
$quote =$this->getOnepage()->getQuote();
$quote->getBaseGrandTotal();
$result = $this->getOnepage()->saveShipping($data, $customerAddressId);
if ($quote->getBaseGrandTotal() < 1000) {
$method = 'inchoo_shipping_fixed';
} else {
$method = 'inchoo_shipping_free';
}
// $method = 'flatrate_flatrate';
$result = $this->getOnepage()->saveShippingMethod($method);
Mage::getSingleton('checkout/type_onepage')->getQuote()->getShippingAddress()-> setShippingMethod($method)->save();
$result['update_section'] = array(
'name' => 'payment-method',
'html' => $this->_getPaymentMethodsHtml()
);
$result['goto_section'] = 'payment';
} else {
$result['goto_section'] = 'shipping';
}
}
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
}
}
}