define field name in JavaScript object literal from variable - javascript

i need to change the field dynamically
this.search = function(search, match) {
var deferred = $q.defer()
search({
size: 10000,
index: "products",
body: {
"query": {
"match": {
[search]: {
"query": match,
// "operator": "and",
type:"phrase"
}
}
}
}
but its showing the error 30:16 error Parsing error: Unexpected token [

You'll have to split it up so you can build the body object dynamically:
var body = {
"query": {
"match": { }
}
};
body.query.match[search] = {
"query": match,
"type": "phrase"
};

This isn't an AngularJS problem - the problem is you are trying to use a Computed Property Name for the object literal when the browser you are using doesn't support it.
Computed Property Name documentation link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
To see the which browsers can & can't use Computed Property Names:
https://kangax.github.io/compat-table/es6/#test-object_literal_extensions_computed_properties

Related

Is it possible in AWS dynamo database to name object keys with dashed strings? or to apply command (update, delete) to dashed string keys?

My scenario is a dynamo database in aws, I've a table containing a structure like the following one:
{
"data": {
"23fc4fa8-0037-4d09-90be-506eed497a15": {
"text": "first text"
},
"4708f80a-e301-48ab-8351-f598c4300600": {
"text": "second text"
}
},
"types": "type",
"order": 3
}
My goal is to delete the second text, I receive from clientside the id 4708f80a-e301-48ab-8351-f598c4300600 so I'm building my call to delete that field only, in order to have this data after the removal operation:
{
"data": {
"23fc4fa8-0037-4d09-90be-506eed497a15": {
"text": "first text"
}
},
"types": "type",
"order": 3
}
This is the code I'm using:
const type = 'type'
const id = '4708f80a-e301-48ab-8351-f598c4300600'
const dynamoBd = new AWS.DynamoDB.DocumentClient()
const params = {
TableName: DB_TABLE,
Key: {
types: type
},
UpdateExpression : `REMOVE data.${id}`
}
await dynamoDbClient
.update(params, (error, _) => {
if (error) {
console.error(`Error: `, error)
return
}
})
.promise()
But I receive this error:
Error: ValidationException: Invalid UpdateExpression: Syntax error; token: "4708", near: ".4708f80a"
I believe the issue is the way this string is build 'REMOVE data.${id}' that parsed look like this 'REMOVE data.4708f80a-e301-48ab-8351-f598c4300600'
Any ideas how to solve this, thanks in advance to everyone who could help me out. Ps. if you find some documentation on aws website about it, could you also post it, because currently I couldn't find it. Thanks again!
This is the way to build the const params, with the support of ExpressionAttributeNames:
The reason is that some keys or values might be keywords or contain special characters (like dash in the example). So ExpressionAttributeNames (for the example) and ExpressionAttributeValues are used to create substitute placeholders of the keys and values.
const params = {
TableName: DB_TABLE,
Key: {
types: type
},
UpdateExpression : `REMOVE #data.#id`,
ExpressionAttributeNames: {
'#data': 'data',
'#id': id
}
}

How to check if object prop exists while of destructuring?

I have this statement :
const {
'xsi:Event': {
'xsi:eventData': [
{
'xsi:call': [
{
'xsi:extTrackingId': [extTrackingId],
'xsi:personality': [personality],
'xsi:internalReleaseCause': [releaseCause],
},
],
},
],
},
} = data
I'm parsing complicate object from some api. On top is real example of object. In some cases, i have same structure, but without property 'xsi:internalReleaseCause', so in this case i cant define a value for releaseCause constant.
Question is how to check if 'xsi:internalReleaseCause' prop exists, on the fly?
const data= {
'Event': {
'eventData': [
{
'call': [
{
'extTrackingId': [],
'personality': [],
'internalReleaseCause': ['hi'],
},
],
},
],
},
}
var { Event: {eventData: [{call:[{extTrackingId:[],personality:[],internalReleaseCause}]}]} } = data;
console.log(internalReleaseCause[0])
we can use this object destruction to identify internalReleaseCause on the fly but you have some special characters (:) in object keys. I am not sure how to escape them but if there is a way you can get rid of them, then the below snippet works and you can identify the object directly. Hope this helps!

Introspection Query is invalid for buildClientSchema

I am trying to convert from an introspection query to a GraphQL schema using the npm GraphQL library.
It keeps stating:
devAssert.mjs:7 Uncaught Error: Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: { ... }
Issue is I am getting it directly from GraphiQL Shopify and can't figure out how to validate my introspection return is correct.
Code:
var introspection = `
{
"data": {
"__schema": {
"types": [
{
"name": "Boolean"
},
{
"name": "String"
},
{
"name": "QueryRoot"
},
{
"name": "Job"
},
{
"name": "ID"
},
{
"name": "Node"
},
{
"name": "Order"
}
]
}
},
"extensions": {
"cost": {
"requestedQueryCost": 2,
"actualQueryCost": 2,
"throttleStatus": {
"maximumAvailable": 1000,
"currentlyAvailable": 980,
"restoreRate": 50
}
}
}
}`;
let schema = buildClientSchema(introspection);
//console.log(schema.printSchema());
I thought the introspection result could be a string? Or is there not enough info to build a schema? Do I need to expand the number of fields? What's the bare minimum needed to exchange an introspection result into a schema?
You should use getIntrospectionQuery to get the complete introspection query needed. If the response you're working with is a string, it should then be parsed to an object before being passed to buildClientSchema -- the function accepts an object, not a string.
Here's an example directly querying a schema using the graphql function -- you'll need to modify it based on how you're actually executing the query.
const { getIntrospectionQuery, buildClientSchema, graphql } = require('graphql')
const schema = new GraphQLSchema(...)
const source = getIntrospectionQuery()
const { data } = await graphql({ source, schema })
const clientSchema = buildClientSchema(data)
Make sure that you are only passing in the data portion of the response. The object you pass in should look like this:
{
__schema: {
// ...more properties
}
}

How to use / reference field values generated in the same json schema

I am trying to create mock data by using the json-server in combination with the json-schema-faker.
I was trying to use the $ref property but I understood that this only references the type and not the exact value.
Is there a way to reuse the exact same value instead of just its type?
The schema I have in mockDataSchema.js file is:
var schema =
{
"title": "tests",
"type": "object",
"required": [
"test"
],
"properties": {
"test": {
"type": "object",
"required": [
"id",
"test2_ids",
"test3"
],
"properties": {
"id": {
"type": "string",
"faker": "random.uuid" // here
},
"test2_ids": {
"type": "array",
"items": {
"type": "string",
"faker": "random.uuid" // here
}
},
"test3": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"faker": "random.uuid" // here
}
}
}
}
}
}
}
};
module.exports = schema;
From this schema I want the id to be the same in all three locations which i have indicated with the comment // here.
Note that I can't use an enum or const as I want to have multiple tests occurrences.
test2_ids will be an array so i would like to include that specific id for the first id and other values of the same type as well..
In the id of test3 i just want the exact same value as the id of test.
Is it feasible what I am trying to achieve?
Or is there a way to change these data in the generateMockData.js file instead of the mockDataSchema.js which includes this schema ?
My generateMockData.js :
var jsf = require('json-schema-faker');
var mockDataSchema = require('./mockDataSchema');
var fs = require('fs');
var json = JSON.stringify(jsf(mockDataSchema));
fs.writeFile("./src/api/db.json", json, function (err) {
if (err) {
return console.log(err);
} else {
console.log("Mock data generated.");
}
});
I'd like to share here a solution that I found. In my case, I required to generate the same value for the fields password and password_confirmation using json-schema-faker, and something that worked for me was, assign a new property in the faker library and put the new property name inside the faker schema. Here the code:
import faker from 'faker';
import jsf from 'json-schema-faker';
// here we generate a random password using faker
const password = faker.internet.password();
// we assign the password generated to a non-existent property, basically here you create your own property inside faker to save the constant value that you want to use.
faker.internet.samePassword = () => password;
// now we specify that we want to use faker in jsf
jsf.extend('faker', () => faker);
// we create the schema specifying the property that we have created above
const fakerSchema = {
type: 'object',
properties: {
password: {
faker: 'internet.samePassword',
type: 'string'
},
password_confirmation: {
faker: 'internet.samePassword',
type: 'string'
}
}
};
// We use the schema defined and voilá!
let dataToSave = await jsf.resolve(fakerSchema);
/*
This is the data generated
{
password: 'zajkBxZcV0CwrFs',
password_confirmation: 'zajkBxZcV0CwrFs'
}
*/

Searching on a variable-defined field with ElasticSearch

Here is the relevant code:
var field = String(querystring.parse(postData).field).toLowerCase();
var qryObj = {
"fields" : view_options,
"query":{
"term" : { field : value}
}
};
The variable 'field' will be a string, like "number", "date", etc. What I want to do is search the index only in the field that is defined in the variable 'field'. This code works if I hardcode the string, like this:
"term" : { "number" : value}
So can someone shed some light on a way to only search a specific field using a predefined variable instead of a string?
You can't use variables as keys in an Object literal. On the left of each :, identifiers themselves become the key's name rather than being evaluated as variables for their values.
console.log({ key: "value" }); // { key: 'value' }
console.log({ "key": "value" }); // { key: 'value' }
You'll have to build the Object first using bracket member operators, then apply it to the query object:
var term = {};
term[field] = value;
var qryObj = {
fields: view_options,
query: {
term: term
}
};
Update:
With ECMAScript 6, Object literals do now support computed keys using bracket notation for the key:
var qryObj = {
fields: view_options,
query: {
term: {
[field]: value
}
}
};

Categories

Resources