i have this function: export async function createNewMember(req, body) { console.log(“—…
- User
i have this function: export async function createNewMember(req, body) { console.log(“— createNewMember”);
const endpointNewMembership = “/v1/memberships:grant”; const CONNECTION = GetStoreConnection(req); console.log(“— CONNECTION createNewMember”, CONNECTION); if (!CONNECTION) { console.error(“CONNECTION PARAMETERS NOT FOUND!!!”); }
const domain = .get(CONNECTION, “url”); console.log(“— domain”, domain); const AuthStr = "Bearer ".concat(.get(CONNECTION, “token”)); console.log(“— AuthStr”, AuthStr);
const urlNewMembershipWithRewards = domain + endpointNewMembership;
const creatMembershipResponse = await axios .post({ url: urlNewMembershipWithRewards, method: “POST”, headers: { Authorization: AuthStr }, data: body, }) .then((response) => { console.log(“— response CreateMembership”, response.data); }) .catch((error) => { console.error(“— ERROR in CREATE MEMBERSHIP on LAVA”, error); });
return creatMembershipResponse; }
which gives me this error:
— ERROR in CREATE MEMBERSHIP on LAVA TypeError [ERR_INVALID_ARG_TYPE]: The “url” argument must be of type string. Received an instance of Object 2023-05-31 10:27:37 │ backend │ at new NodeError (node:internal/errors:399:5) 2023-05-31 10:27:37 │ backend │ at validateString (node:internal/validators:163:11) 2023-05-31 10:27:37 │ backend │ at Url.parse (node:url:183:3) 2023-05-31 10:27:37 │ backend │ at Object.urlParse [as parse] (node:url:154:13) 2023-05-31 10:27:37 │ backend │ at dispatchHttpRequest (C:\dev\shopify\Lava-shopify-adapter\web\node_modules\axios\lib\adapters\http.js:133:22) 2023-05-31 10:27:37 │ backend │ at new Promise () 2023-05-31 10:27:37 │ backend │ at httpAdapter (C:\dev\shopify\Lava-shopify-adapter\web\node_modules\axios\lib\adapters\http.js:49:10) 2023-05-31 10:27:37 │ backend │ at dispatchRequest (C:\dev\shopify\Lava-shopify-adapter\web\node_modules\axios\lib\core\dispatchRequest.js:58:10) 2023-05-31 10:27:37 │ backend │ at Axios.request (C:\dev\shopify\Lava-shopify-adapter\web\node_modules\axios\lib\core\Axios.js:109:15) 2023-05-31 10:27:37 │ backend │ at Axios.httpMethod [as post] (C:\dev\shopify\Lava-shopify-adapter\web\node_modules\axios\lib\core\Axios.js:144:19) { 2023-05-31 10:27:37 │ backend │ code: ‘ERR_INVALID_ARG_TYPE’ 2023-05-31 10:27:37 │ backend │ }
- Assistant
The error message states that the "url" argument must be of type string, but it has received an object instead. In the function code, the "url" argument is being constructed using the "domain" variable and the "endpointNewMembership" variable. It is possible that one of these variables is not a string, causing the error.
To fix the error, you can try the following steps:
- Check the value of the "domain" variable and make sure it is a string.
- Check the value of the "endpointNewMembership" variable and make sure it is a string.
- Try logging the constructed URL using console.log to see if it looks correct.
- Pass the "url" argument to the axios.post method as a string instead of an object. Change the code to:
const createMembershipResponse = await axios.post( urlNewMembershipWithRewards, { headers: { Authorization: AuthStr }, data: body, } ) .then((response) => { console.log("--- response CreateMembership", response.data); }) .catch((error) => { console.error("--- ERROR in CREATE MEMBERSHIP on LAVA", error); }); return createMembershipResponse;This should fix the error and allow the function to execute without issues.
- User
what if i call urlnewmembershipwithrewards.stringify
- Assistant
urlnewmembershipwithrewardsis a string, not an object, so thestringifyfunction is not applicable here. Thestringifyfunction is used to convert a JavaScript object to a JSON string.If you try to call
stringifyon a string, you will get aTypeErrorbecause the string type does not have astringifymethod.Instead of calling
stringifyonurlnewmembershipwithrewards, you can simply pass it directly as the URL argument in theaxios.postmethod, like this:const creatMembershipResponse = await axios .post(urlNewMembershipWithRewards, { headers: { Authorization: AuthStr }, data: body, }) .then((response) => { console.log("--- response CreateMembership", response.data); }) .catch((error) => { console.error("--- ERROR in CREATE MEMBERSHIP on LAVA", error); }); return creatMembershipResponse;This will use
urlNewMembershipWithRewardsas a string URL for the HTTP request and pass theheadersanddataas the request body. - User
if i pass a json like "Marius3 Placinta3" i get printed as lastName: '3 Placinta 3' and as name 'Marius3' instead of having printed as lastname 'Placinta3' in this method: const lastName = .join(.slice(.words(.get(req.body, "customer.name")), 1)," ");
- Assistant
The issue you are facing is related to the way you are constructing the
lastNamevariable. The_.wordsfunction from the Lodash library splits a string into an array of words, using whitespace as a delimiter. In your case, the input"Marius3 Placinta3"will be split into["Marius3", "Placinta3"].The
_.slicefunction is then used to create a sub-array of the words starting from index 1 (i.e., the second word), which will include only"Placinta3". Finally, the_.joinfunction is used to join the words in the sub-array using a whitespace as a separator, resulting in"Placinta3".To get the correct last name from the input
"Marius3 Placinta3", you need to modify the code that constructs thelastNamevariable. One way to do this is to split the input using a regular expression that matches any digits () or whitespaces () and then remove the empty elements from the resulting array. Here's an example: - User
this function gives me error saying "The 'url' argument must be of type string. Received an instance of Object". export async function createNewMember(req, body) { console.log("--- createNewMember");
//to be removed, just for test const testUrl = "https://kings-membership.lava.ai/v1/memberships:grant";
const endpointNewMembership = "/v1/memberships:grant"; const CONNECTION = GetStoreConnection(req); console.log("--- CONNECTION createNewMember", CONNECTION); if (!CONNECTION) { console.error("CONNECTION PARAMETERS NOT FOUND!!!"); }
const domain = .get(CONNECTION, "url"); console.log("--- domain", domain); const AuthStr = "Bearer ".concat(.get(CONNECTION, "token")); console.log("--- AuthStr", AuthStr);
const urlNewMembershipWithRewards = domain + endpointNewMembership; console.log("----- CONTROLLO URL ", urlNewMembershipWithRewards)
const creatMembershipResponse = await axios .post({ url: testUrl, method: "POST", headers: { Authorization: AuthStr }, data: body, }) .then((response) => { console.log("--- response CreateMembership", response.data); }) .catch((error) => { console.error("--- ERROR in CREATE MEMBERSHIP on LAVA", error); });
return creatMembershipResponse; }
- Assistant
The error message "The 'url' argument must be of type string. Received an instance of Object" occurs because you are passing an object instead of a string as the
urlparameter to theaxios.postmethod. Theaxios.postmethod takes two parameters: the first is a string URL and the second is the HTTP request options, which is an object, but you are currently passing an object as the first parameter.To fix this error, you should change the code as follows:
const createMembershipResponse = await axios .post( urlNewMembershipWithRewards, // pass the URL as a string body, // pass the request data as the second parameter { method: "POST", headers: { Authorization: AuthStr }, } ) .then((response) => { console.log("--- response CreateMembership", response.data); }) .catch((error) => { console.error("--- ERROR in CREATE MEMBERSHIP on LAVA", error); }); return createMembershipResponse;Here, you pass the
urlNewMembershipWithRewardsvariable as the first parameter, thebodyvariable as the second parameter, and the request options as the third parameter. This should fix the error and allow the function to execute correctly. - User
i have an .env file where i saved a variable and i want to read it from a .js file in react
- Assistant
To access an environment variable from a JavaScript file in React, you can use the
process.envobject.Assuming the name of your environment variable is
MY_ENV_VAR, you can access its value as follows:const myEnvVar = process.env.MY_ENV_VAR;This will give you the value of the environment variable, which you can use in your JavaScript code.
Note that you need to make sure that the environment variable is set in your environment before you can access it in your JavaScript code. You can set the value of the environment variable either in a
.envfile or in your shell environment. If you are using a.envfile, make sure that it is in the root folder of your project and that it is named.env. Thecreate-react-apptool automatically loads the.envfile and sets the environment variables when you start the development server or build the project.Also, make sure that you have installed the
dotenvpackage in your project by running the following command in the terminal: - User
i have a form where there is Name Surname and Email, i send this data passing Marius3 as name and Placinta3 as surname and when i read them the json which comes back contains as name "Marius3" and surname "Marius3 Placinta3", i had to use lodash methods to extract the surname adding spaces to each word, the problem is that if the string contains number i get "3 Placinta 3" as surname, but i Should get "Placinta3" or even better "Placinta". This are the methods i wrote: const lastName = .join(.slice(.words(.get(req.body, "customer.name")), 1)," ");
How can i improve it without using slice and maybe using something like stringreplace? - Assistant
To extract the surname from a string that contains both the first and last name, you can use a regular expression to match the last word that contains only letters and optional digits. Here's an example:
const fullName = _.get(req.body, 'customer.name'); const lastNameMatch = fullName.match(/[a-zA-Z]+\d*$/); const lastName = lastNameMatch ? lastNameMatch[0] : "";Here, the
fullNamevariable contains the full name (i.e. both the first and last name). Thematchmethod is used to extract the last word that contains only letters ([a-zA-Z]) and optional digits (\d*) at the end of the string ($). This regular expression matches any combination of letters and digits at the end of the string, as long as the letters come first.The result of the
matchmethod is an array that contains the matched string and any captured groups. In this case, there is only one captured group, which is the matched string itself. The[0]index is used to extract the matched string from the array. If there is no match (i.e. the full name contains no letters), an empty string is returned as the last name. - User
i want to avoid using the regular expression, i want to use string replace to replace numbers in "" and then split the words and get the surname (which could be from example composed of more words). I can have the case where the name is Marius Iulian and the surname is Placinta, i need extract Placinta. Make it as easy as possible
- Assistant
Here's one way to extract the surname using string manipulation:
const fullName = _.get(req.body, 'customer.name'); const lastNameWithNumbers = _.last(fullName.split(" ")); const lastName = lastNameWithNumbers.replace(/\d+/g, '');This code first retrieves the full name from the request body using Lodash. It then splits the full name into words using the space character as the separator and takes the last word as the string that contains the last name and any digits.
Finally, we use the
replacemethod to remove any digits in the last name string. The regex/\d+/gmatches any consecutive digits in the string, and the''(empty string) replaces them, effectively removing them from the string. This converts the string "Placinta3" to "Placinta".Note that this approach assumes that the last name is always the last word in the full name. If you have cases where the full name includes a middle name or multiple last names, you will need to modify the code accordingly to extract the correct last name.
- User
i want a solution which based on the Name (which arrives correct in the json containing for example name and middle name), it should remove the words containing the name strings inside surname and extract the leftover
- Assistant
One way to remove the words containing the name strings inside surname is by splitting the full name into words and removing any words that match the first name or any middle name(s). After that, you can join the remaining words to obtain the last name.
Here's an example implementation:
const fullName = _.get(req.body, 'customer.name'); const nameWords = _.words(fullName); const firstName = nameWords[0]; const middleNames = nameWords.slice(1, -1); const surnameWords = _.words(_.last(nameWords)); const surnameWithoutNames = _.reject(surnameWords, word => _.includes([firstName, ...middleNames], word) ); const lastName = _.join(surnameWithoutNames, " ");Here, the code first retrieves the full name from the request body using Lodash. It then splits the full name into words using the method.