I am using mongoosastic npm module. While truncating index I am getting
TypeError: Unable to build a path with those params. Supply at least index
The code I'm using
For Truncate :
var tagModelJS = require('../DaoModel/TagModel.js');
var TagModel = tagModelJS.getTagModel();
TagModel.esTruncate(function (err) {
if (err) {
console.log("ERROR : while removing data from elastic search.")
throw err;
}
});
TagModel :
var TAGS;
module.exports = {
createSchemaAndGetModel : function (mongoose, mongoosastic, Schema) {
//create schema
var tagSchema = new Schema({
tagDetail : String,
userIds : [], //list of user ids
tagName : {
type : [String],
es_indexed : true
} // field level
});
tagSchema.plugin(mongoosastic)
//create model
TAGS = mongoose.model('TAGS', tagSchema);
console.log("Tag model ready....");
},
getTagModel : function () {
return TAGS;
}
};
Any help would be greatly appreciated.
Related
My table looks like [alias, inheritedLdap, LdapGroup ] here alias is the string and the LdapGroup is the List form eg: [{S:aws}]. So basically my use case is to get the list of aliases whose ldapGroup is aws. Here the alias is the partition key, we don't have the sort key. So I need to write a method which takes the ldapGroup as the parameter and filter the list of the alias when the ldapGroup is aws. But ldapGroup doesn't contain scalar values. I tried to implement the code but its failing when I try to compile,
public async getMemberList(): Promise<any> {
const input: any = {
TableName: UserInfoDao.TABLE_NAME, // use this from the constants
ProjectionExpression: "alias",
FilterExpression: "#l = :ldapGroups",
ExpressionAttributeNames: {
"#l": "ldapGroups"
},
ExpressionAttributeValues: {
":ldapGroups": "PPOA"
}
};
try {
const ddbClient = DynamDBClient.getInstance();
return await ddbClient.scan(input);
} catch (error) {
const message = `ERROR: Failed to retrieve alias for given ldapGroups:
ERROR: ${JSON.stringify(error)}`;
error.message = message;
throw error;
}
}
But when I use the ScanCommandOutput and ScanCommadInput in my code instead of any, its shows the error that the
Type 'Record<string, AttributeValue>[] | undefined' is not assignable to type 'ScanCommandInput'. Type 'undefined' is not assignable to type 'ScanCommandInput'
Property '$metadata' is missing in type 'Request<ScanOutput, AWSError>' but required in type 'ScanCommandOutput'.
Can someone help me with this one.
I am expecting whether my approach is correct or not
This works for me, I made some edits you your example:
import { DynamoDBClient } from "#aws-sdk/client-dynamodb";
import { ScanCommand, ScanCommandInput } from "#aws-sdk/lib-dynamodb";
const client = new DynamoDBClient({
region: 'eu-west-1',
});
class MyClass {
public getMemberList(): Promise<any> {
const input: ScanCommandInput = {
TableName: 'Test1',
// ProjectionExpression: "alias",
FilterExpression: "contains(#l, :ldapGroups)",
ExpressionAttributeNames: {
"#l": "ldapGroups"
},
ExpressionAttributeValues: {
":ldapGroups": "aws"
}
};
try {
return client.send(new ScanCommand(input))
} catch (error) {
const message = `ERROR: Failed to retrieve alias for given ldapGroups: ERROR: ${JSON.stringify(error)}`;
error.message = message;
throw error;
}
}
}
const c = new MyClass();
c.getMemberList().then(res => console.log(res)).catch(err => console.log(err));
Note: I'm new to GraphQL.
Challenge: I use the Shopify Storefront API to create a selectbox of all our products. When a user selects a product in this selectbox, its metafields should be displayed on the page.
I managed to create that selectbox. But how would i display the product-specific data when a choice was made in the selectbox? See current code:
function apiCall(productQuery) {
return fetch('https://store//api/2022-04/graphql.json',
{
method: 'POST',
headers: {
'Content-Type': 'application/graphql',
'X-Shopify-Storefront-Access-Token': "xxx"
},
"body": productQuery
}
)
.then(
response => response.json()
);
}
function getProducts() {
const productQuery = `{ products(first: 250) { edges { node { id handle title } } } }`;
return apiCall(productQuery);
}
$(document).ready(function() {
const product_selector_container = $('.product_selector_container');
getProducts().then(response => {
product_selector_container.prepend("<select name='product_compatibility_selector' id='product_compatibility_selector'></select>");
const productSelect = $('#product_compatibility_selector');
const productSelectResult = $("#product_compatibility_result");
response.data.products.edges.forEach(product => {
const optionValues = `<option value="${product.node.handle}">${product.node.title}<option>`;
productSelect.append(optionValues);
});
$("#product_compatibility_selector").on('change', function() {
var selected = $(this).find('option:selected').text();
var selectedVal = $(this).find('option').val();
$(".chosen_product_title").text(selected);
response.data.products.edges.forEach(product => {
// HOW DO I REFERENCE THE CURRENT CHOSEN PRODUCT TO OUTPUT VARIOUS NODES?
const compatibility_result = `${product.node.title}`;
productSelectResult.append(compatibility_result);
});
});
});
});
Now that you have the handle of the selected produt to retrieve all the metafields of that produt you need to run another query, using the "query" parameter, something like this
{
products(first: 1, query:"handle:your-handle"){
edges{
node{
metafields(first:10){
edges{
node{
value
key
}
}
}
}
}
}
}
or
{
product(handle:"your_handle"){
title
metafield(key:"your_key", namespace:"your_space"){
value
}
}
}
If you want to parametrize your handle you may want to introduce variables in your query, like this
query($handle:String){
product(handle:$handle){
title
metafield(key:"x",namespace:"y"){
id
value
}
}
}
and with the variable object being like
{"handle":"your-handle"}
In the request instead of just sending the query you send an object like
{"query" : your-query, "variables" : variable-object}
Why the following query result is wrong and null returns
const Mutation = {
createJob: (root, { input}) => {
const id = db.jobs.create({ input });
return db.jobs.get(id);
},
};
I'm having this GraphQL query from headless Wordpress in Nexjs via WpGraphQl plugin:
export const GET_POSTS_BY_CATEGORY_SLUG = gql`
query GET_POSTS_BY_CATEGORY_SLUG( $slug: String, $uri: String, $perPage: Int, $offset: Int ) {
${HeaderFooter}
page: pageBy(uri: $uri) {
id
title
content
slug
uri
seo {
...SeoFragment
}
}
categories(where: {slug: $slug}) {
edges {
node {
slug
posts: posts(where: { offsetPagination: { size: $perPage, offset: $offset }}) {
edges {
node {
id
title
excerpt
slug
featuredImage {
node {
...ImageFragment
}
}
}
}
pageInfo {
offsetPagination {
total
}
}
}
}
}
}
}
${MenuFragment}
${ImageFragment}
${SeoFragment}
`;
And this is my getStaticProps function:
export async function getStaticProps(context) {
const { data: category_IDD } = await client.query({
query: GET_POSTS_BY_CATEGORY_SLUG,
});
const defaultProps = {
props: {
cat_test: JSON.parse(JSON.stringify([category_IDD])),
},
revalidate: 1,
};
return handleRedirectsAndReturnData(defaultProps, data, errors, "posts");
}
If i pass it like this in props:
const defaultProps = {
props: {
cat_test: category_IDD,
},
i get an error saying:
SerializableError: Error serializing `.cat_test` returned from `getStaticProps` in "/category/[slug]". Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.
But when i JSON.parse as the code above, i get null
Whats wrong with this query?
Just noticed that the $slug is an array of strings, so here should be:
query GET_POSTS_BY_CATEGORY_SLUG( $slug: [String], $uri: String, $perPage: Int, $offset: Int )
instead of $slug: String
You're not actually passing the $slug variable to the query.
For instance if your page route is /category/[slug].js your getStaticProps should look something like this.
export async function getStaticProps(context) {
const { slug } = context.params;
const { data: category_IDD } = await client.query({
query: GET_POSTS_BY_CATEGORY_SLUG,
variables: { slug },
});
const defaultProps = {
props: {
cat_test: JSON.parse(JSON.stringify([category_IDD])),
},
revalidate: 1,
};
return handleRedirectsAndReturnData(defaultProps, data, errors, "posts");
}
I'm trying to validate my Model but i miss something and i don't know what is it.
It is my module and his validation for email.
module.exports = function(sequelize, DataTypes){
return sequelize.define("Scanner",
{
id : {
primaryKey : true,
autoIncrement : true,
type : DataTypes.INTEGER
},
email : {
type : DataTypes.STRING,
isUnique :true,
allowNull:false,
validate:{
isEmail : true
}
},
pin : {
type : DataTypes.INTEGER
}
},{
tableName : 'scanner'
});
};
When i'm trying to Find an object with parameters (pin + email) if i put this.email = ssdf.sdf , my query is launched and i would like to check first if my params are correct.
Scanner.prototype.getScannerByCredentials = function(callback){
//Send only Field id and email
_Scanner.find({ where: { email : this.email, pin :this.pin},attributes:['id','email'] }).success(function(scanner) {
return callback(null, scanner);
}).error(function(error){
console.log(error);
return callback(error, null);
});
};
I tried with validate() method but i've got as error : Object [object Object] has no method 'validate' and when i'm made a console.log(_Scanner); i saw my function validate() so i don't know why that's doesn't work..
Scanner.prototype.getScannerByCredentials = function(callback){
//Send only Field id and email
_Scanner.find({ where: { email : this.email, pin :this.pin},attributes:['id','email'] }).validate().success(function(scanner) {
return callback(null, scanner);
}).error(function(error){
console.log(error);
return callback(error, null);
});
};
I'm reading the docs and try a lot of thing founded on the net so if someone could explain to me what's wrong, it will be really nice.
Thanks a lot in advance.
EDIT : FOUND !
My solution if you're interested :)
My Models :
module.exports = function(sequelize, DataTypes){
return sequelize.define("Scanner",
{
id : {
primaryKey : true,
autoIncrement : true,
type : DataTypes.INTEGER,
allowNull : false
},
email : {
type : DataTypes.STRING,
isUnique :true,
allowNull:false,
validate:{
isEmail : true
}
},
pin : {
type : DataTypes.INTEGER
}
},{
tableName : 'scanner',
classMethods:{
isValid : function(objScanner) {
return this.build(objScanner).validate() ? true : false ;
}
}
});
};
My credentials Method :
Scanner.prototype.getScannerByCredentials = function(callback){
//MODIF THIS PART / NEED TO IMPROVE
var error = _Scanner.build({ email : this.email, pin : this.pin}).validate();
if(error === null){
_Scanner.find({ where: { email : this.email, pin :this.pin},attributes:['id','email'] }).success(function(scanner) {
console.log(scanner);
return callback(null, scanner);
}).error(function(error){
console.log(error);
return callback(error, null);
});
}
else
return callback(error,null);
};
And my generic update method (bonus) :
Scanner.prototype.update= function(callback){
var self = this;
_Scanner.find(this.id).success(function(scannerFound){
if(scannerFound){
//Set old Values by New Values : only values changed
scannerFound.dataValues = ormize(self,scannerFound.dataValues);
//Check validation Fields before insert DB
if(_Scanner.isValid(scannerFound)){
scannerFound.save().success(function(){
return callback(true);
}).error(function(error){
return callback(false);
});
}else
return callback(false);
}else
return callback(false);
}).error(function(error){
console.log(error);
return callback(false);
});
};
If you have any advice with my code it will be grateful too :)
Thank a lot in advance
What version do you use? This should have been fixed
The field should look like this.
isEmail: {msg: 'Reason'}