How to get string value from query parameters - javascript

I'm trying to get the string value within a class-object variable called question5. I'm trying to access this variable like so in the front-end.
axios.get("http://localhost:3001/users/questionaire/?getquestion5=question5")
.then((res) => console.log(res.data))
Also, this is how it looks inside of the object in the js file.
const [answerslist, setAnswerslist] = useState(
{
question1: "",
question2: "",
question3: "",
question4: "",
question5: "",
question6: "",
question7: "",
question8: ""
}
)
However, when queried and log onto the console from the backend it literally just logs the string 'question5.' In other words, the string is literally just question5 not the text being added to it.
router.route('/questionaire').get((req, res) =>{
console.log(req.query.getquestion5)
User.find({email: req.query.getquestion5}, function (err, docs){
if(docs){
console.log("Email exist")
console.log(`${req.query.getquestion5}`);
console.log(docs)
}
else{
console.log(req.query.getquestion5)
console.log("Email doesnt exist")
}
}).clone().catch(function(err){console.log(err)})
})
Any reason why this might be the case?

If your intention is to send the answerlist.question5 state value in the query string getquestion5 parameter, try using Axios' params config option
params are the URL parameters to be sent with the request
Must be a plain object or a URLSearchParams object
NOTE: params that are null or undefined are not rendered in the URL.
axios.get("http://localhost:3001/users/questionaire", {
params: {
getquestion5: answerslist.question5
}
});
You'd then receive whatever value was in state at the time the request was made into the req.query.getquestion5 property.
Using params is preferable to interpolating strings directly into the URL since it will automatically URL-encode values that otherwise would not be valid. The equivalent safety measure would look like this...
axios.get(
`http://localhost:3001/users/questionaire?getquestion5=${encodeURIComponent(answerslist.question5)}`
);
which gets unmaintainable with more parameters.

Related

SUPABASE/JavsScript: how to DELETE user metadata?

Is there a way to delete user metadata in Supabase? They offer update() option, but it seems it works as patch request, so I can't find a way to delete it.
Here's their code:
```const { user, error } = await supabase.auth.update({
data: { hello: 'world' }
});```
I tried to do this:
```const { user, error } = await supabase.auth.update({
data: {}
});```
But is doesn't do anything.
Can metadata be deleted?
Thanks
It is possible to set the metadata field to an empty JSON object (i.e. {}) but, currently, there is no way to set it to NULL. Also, you would need to know all the fields that are already stored in the metadata because you need to remove each one explicitly.
If this works for your scenario, the way to do it is to send a data object where each field that you want removed has a value of null.
For example, if you have the following JSON in your metadata: { 'field1': 2, 'field2': 'something' }, you can set the metadata to an empty JSON object like this:
supabase.auth.update({ 'data': { 'field1': null, 'field2': null } });

Vue and Javascript API/Object/Array manipulation for searching values

Edit to clarify:I have an object from an API response that I get using the mounted function, data is saved not displayed yet. I need to be able to filter that data by allowing a user to input text in an input box before showing it on the page, then find where that keyword was used in a specific key value(name). Then show the results on a page but include other key/value pairs from the api array. This is what the api response looks like:
class: (...)
facets: (...)
numberFound: (...)
results: Array(202)
[0 … 99]
0:
class: "SearchResult"
contentGuid: "7f19462f-6c25-43a9-bdb5-479f5f42fbde"
dateUpdated: "2018-03-27T16:46:31Z"
description: "Converting a Word Document to Adobe Acrobat PDF Learning Services Converting a Word Document to Adobe Acrobat PDF Enterprise Converting a Word Document to Adobe Acrobat PDF / Reference ..."
document: Object
documentGuid: "035f5c69-d406-4c16-86ca-de12773a0963"
documentId: 154424
documentVersionId: 44043
fileId: 74213
format: "PDF"
id: "Document#1#44043"
isFavorite: false
languages: "English"
name: "Converting a Word Document to Adobe Acrobat PDF"
numberOfIndexedCoobs: 0
numberOfSharedLinks: 1
packageType: "PDF"
previewId: 74213
publicLinkTokens: Array(1)
resourceType: "Other"
score: 0.0054571675
snippets: Object
updatedById: 994
updatedByName: "Michael"
versionName: "3"
For example if someone enters "Adobe" in the search box, I would need to search for the word "adobe" in the name value for the entire object, and only show the ones that have "abobe" somewhere in the name value.
My thought was to get the document name split it, then do an includes() to check for the search term. This works but I can't seem to figure out how to get it all to work together and get the results on the screen, plus get additional information, such as document Id from the original results. this is what I have so far:
async getResults() {
return axios
.get(this.url, {
headers: {
"Content-Type": "application/json",
"Bravais-prod-us-Context": this.getCookie(),
},
})
.then((res) => {
this.search = res.data;
this.search.results.forEach((doc) => {
this.results = doc.document.name
.toLowerCase()
.split(" ")
.includes(this.termSearch.toLowerCase());
console.log(doc.document.name.split(" "));
console.log(this.results);
});
})
.catch((error) => console.log(error));
},
I need to show the original title(some words and acronyms are capitalized) plus the doc id(for url links) and a description, all of this info is in the initial api response.
<div v-for="" v-bind:key="">
{{ ???? }}
</div>
That works in the console but how do I get this back together and on the screen?? Any help is appreciated, not looking for someone else to do my coding, just need some advice.
I would start by diving your logic. At the moment you have a single function that makes an api call and then searches through the results. It would be better suited to have the api call in a separate method so that if the user searches multiple times it doesn't call the api each time. We can easily solve this by adding an extra method that checks if the results object is populated and decides which methods to call.
Casting all strings to lowercase is a good idea to normalize the data. There might be other ways but this works for it's intended purpose. However, splitting a string is unecessary as the includes() method searches through the whole string. See the MDN docs for String.prototype.includes()
To search within an array you can use the filter() method, which will create a new array with all elements that pass the implemented test. See the MDN docs for Array.prototype.filter().
With this in hand, we can write our logic as:
async handleSearch(searchString) {
if (!this.results.length) {
this.getResults()
}
this.searchResults(searchString)
},
async getResults() {
return axios.get(this.url, {
headers: {
"Content-Type": "application/json",
"Bravais-prod-us-Context": this.getCookie(),
},
}).then((res) => {
this.results = res.data.results
}).catch((error) => console.error(error));
},
searchResults(searchString) {
this.filteredResults = this.results.filter(item => {
let name = item.name.toLowerCase();
let searchTerm = searchString.toLowerCase();
return this.name.includes(searchTerm)
})
}
Your input field will call the handleSearch() method, and then you can write you html as such:
<div v-for="result in filteredResults" :key="result.id">
<p>Name: {{result.name}}</p>
<p>Description: {{result.description}}</p>
</div>

Associating xxxx_id with xxxx.id

I am running into a problem where when I submit a "property listing" I get this response:
{"owner_id":"Batman","address":"test","state":"test","sale_price":"test"}
The thing is "owner_id" is supposed to equal or associate with owner's id in a different table/JSON file (e.g owner_id = owner.id), not a string in this case which is why the object is not saving on the back-end.
Is anyone in vanilla JavaScript able to show me an example on how to associate owner_id and owner.id?
It'd be more like :
{
owner: {
id: "Batman"
},
address: "test",
state: "test",
sale_price: "test"
}
You should take a look at : https://www.w3schools.com/js/js_json_objects.asp
EDIT: Not sure how you're fetching this data but it seems like you want to handle the response you're getting.
Here is a simple GET request using the fetch api:
fetch('http://example.com/heroes') //this is the path to your source where you're getting your response data
.then((response) => {
return response.json();
//above you return a promise containing your response data
//you can also handle your response before declaring it in a var here
})
.then((myJson) => {
//you have stored your response data as a var myJson
console.log(myJson);
//here you can work your response data in any way you need
// to show an example (not that you would do this) I've provided a owner object that checks if it's property is equal to the incoming data
var owner = {
"id": Batman,
}
if ( myJson.owner_id === owner.id ) {
//do something here
}
});
More info here.

Apollo Server, Graphql - Must provide query string

Im not sure what im doing wrong here? I've been stuck now for soem time on getting my mutations to run with my apollo-server-lambda in my serverless setup, my queries works fine bu when i try to run a query like this:
{ "mutation": "{ signIn(username: \"SomeUser\", password: \"SomePassword\" ) { token } }" }
I just get the message: " Must provide query string." status 400.
I've set up my resolver like so:
const resolvers = {
Query: {
users: async (_, args, ctx) => User.load(args, ctx)
},
Mutation: {
signIn: async (_, { username, password }, ctx) => Auth.signIn({ username, password }, ctx)
}
};
For additional infor here is my typeDefs:
const typeDefs = gql`
type User {
id: ID!,
firstname: String,
lastname: String,
username: String,
createdAt: String,
role: String
}
type AuthToken {
token: String
}
type Query {
hello: String,
users(id: Int): [User]
}
type Mutation {
signIn(username: String!, password: String!): AuthToken!
}
`;
I'm using postman to test my graphql endpoint and my content type is application/json
I dont know if any one here can tell me what im doing wrong, i tryed to move it all to Query resolver, and it works replace "mutation" with "query" then but it dosent make sens to me using the "query" here and i guess later on when i actually want to use the Mutation to mutate data i would need this to work anyway?
Can any one tell me where im wrong here?
EDIT
I installed: graphql-playground-middleware-lambda and set up the serverless setup with: https://github.com/prisma/graphql-playground#as-serverless-handler and if i use Graphiql it works as intented, but im still interested if any one knows whats wrong with the json i send via postman?
When sending the request, your request body should be a properly-formatted JSON object, with a query property (and optionally, a variables property if including variables):
{
"query": "<GraphQL Document>",
"variables {},
}
This is the case whether the operation itself is a query or a mutation.
The actual value of the query property above must be a syntactically correct document, as outlined in the GraphQL specification. A document will typically consist of a single operation definition (either a query or a mutation) that includes all the requested fields for that operation. The document will also include fragments, if using any.
An operation definition looks like this:
OperationType [Name] [VariableDefinitions] [Directives] SelectionSet
So you could have a document like this:
mutation SomeMutation {
signIn(username: "SomeUser", password: "SomePassword") {
token
}
}
Here, the type of the operation is mutation, the name is SomeMutation and everything between the outermost set of curly brackets is the selection set. If you had any variables, their types would be declared in parentheses before the selection set.
The operation name is optional, but it's helpful to include it for debugging purposes on the backend. Technically, the operation type can be omitted as well, in which case GraphQL simply assumes the type is a query. For example, this is still a valid document:
{
users {
id
}
}
and is equivalent to
query SomeName {
users {
id
}
}
The former is referred to as query shorthand. Obviously, this cannot be used for mutations, so mutations must always explicitly state their operation type. A complete example:
{
"query": "mutation SomeName ($username: String!, $password: String!) { signIn(username: $username, password: $password) { token } }",
"variables {
"username": "SomeUser",
"password": "SomePassword"
},
}

DynamoDB putItem ConditionExpression "boolean" true

am trying to do a ConditionExpression in a DynamoDB put to check whether a stored boolean is true (in this example, whether the user is already verified don't run the put), i'm using the javascript DocumentClient SDK (thanks to #shimon-tolts), the code looks like:
var query = {
TableName: tableName,
Item: {
email: email,
verified: false,
verifyToken: token
},
ConditionExpression: 'attribute_exists(email) AND verified = :bool',
ExpressionAttributeValues: {
":bool":"false"
}
};
dynamodb.put(query, function(err, data){
if (err) return fn(err)
fn(null, data);
});
Which doesn't work, it fails the condition check no matter what the call.
Pretty much what I need (in pseudocode):
IF email already exists AND verified equals false
THEN allow PUT
IF email already exists AND verified equals true
THEN don't allow PUT
IF email does not exist
THEN allow PUT
Any ideas?
I suggest using DocumentClient as it works with javascript objects.
To do a condition expression you have to specify the ExpressionAttributeNames and ExpressionAttributeValues for example::
ConditionExpression: "#yr <> :yyyy and title <> :t",
ExpressionAttributeNames:{"#yr":"year"},
ExpressionAttributeValues:{
":yyyy":year,
":t":title
}
You can see more examples here and read more here
I finally got this to work after figuring out the right ExpressionAttributeValues:
dclient.scan(TableName='bix-workflow-images',
FilterExpression="wgs = :t or attribute_not_exists(wgs)",
ExpressionAttributeValues={':t':{'BOOL':True}})
I am stumbling about this because I have a similar problem and although this is a year old, for me it looks like your boolean shouldn't be a string:
ExpressionAttributeValues: {
":bool": "false"
}
Instead:
ExpressionAttributeValues: {
":bool": false
}
Have you tried it that way?

Categories