I need to write a customizer for mergeWith. I've used defaultsDeep before and it worked exactly the way I want it to, except that defaultsDeep also merge nested arrays. I have 2 objects.
const baseObject = {
firstElement: { data: undefined },
secondElement: {
name: 'Canada',
items: [
{ city: 'Toronto', code: 12334},
{ city: 'Vancouver ', code: 33245}
]
}
};
const defaultObject = {
firstElement: { data: '13.01.2018'},
secondElement: {
name: 'Bresil',
items: [
{ city: 'Rio', code: 67584},
{ city: 'Manaus ', code: 90845},
{ city: 'Salvador ', code: 36745}
]
}
};
and when I do defaultsDeep(baseObject, defaultObject)
I get:
{
firstElement: { data: '13.01.2018' },
secondElement: {
name: 'Canada',
items: [
{city: 'Toronto', code: 12334},
{city: 'Vancouver ', code: 33245},
{city: 'Salvador ', code: 36745}]
}
};
with mergeWith(mergeWith(baseObject, defaultObject, (ObjValue) => ObjValue))
I get:
{
firstElement: { data: undefined },
secondElement: {
name: 'Canada',
items: [
{city: 'Toronto', code: 12334},
{city: 'Vancouver ', code: 33245}]
}
};
Please help me to write customizer for mergeWith, I would be very appreciated 🙂
I expect :
{
firstElement: { data: '13.01.2018' },
secondElement: {
name: 'Canada',
items: [
{city: 'Toronto', code: 12334},
{city: 'Vancouver ', code: 33245}]
}
}
I found some resolving, and I understand that some lines no have sens, but it's work somehow :
const customizer = (objValue, key) => {
if (isArray(key) || objValue?.subItems) return objValue;
if (key) return;
return objValue;
};
The customizer function of _.mergeWith() should return the value that you want or undefined, if you would like _.mergeWith() continue merging nested objects:
const { isArray, isObject, isUndefined, mergeWith } = _;
const customizer = (a, b) => {
if(isArray(a)) return a;
return isObject(a) || isUndefined(a) ? undefined : a;
}
const baseObject = {"firstElement":{},"secondElement":{"name":"Canada","items":[{"city":"Toronto","code":12334},{"city":"Vancouver ","code":33245}]}};
const defaultObject = {"firstElement":{"data":"13.01.2018"},"secondElement":{"name":"Bresil","items":[{"city":"Rio","code":67584},{"city":"Manaus ","code":90845},{"city":"Salvador ","code":36745}]}};
const result = mergeWith(baseObject, defaultObject, customizer);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Related
I'm using Elasticsearch js to make a search engine, like so:
let jobs = await client.search({
index: 'index',
type: 'doc',
body: {
query: {
bool: {
must: [
{
match: {
title: 'test'
}
}
]
}
}
}
});
if the title has 'test' in it , it will show, but when it has something like 'hello this is/test' it wont show up, how do I fix it?
You can surround the string with *:
let jobs = await client.search({
index: 'index',
type: 'doc',
body: {
query: {
bool: {
must: [
{
match: {
title: '*test*'
}
}
]
}
}
}
});
Hi guys I have this code :
let test = await client.search({
index: 'test',
type: 'doc',
body: {
query: {
match: {
title: 'something',
}
}
}
});
this code is searching by 1 query which is title: 'something' , but I want to change it to search with multiple keys, for example:
let test = await client.search({
index: 'test',
type: 'doc',
body: {
query: {
match: {
title: 'something',
desc: 'some Qualifications'
}
}
}
});
but this code doesn't work and I can't find anything that will work like that, can anyone help?
You need to combine all the match queries using a bool/must query, like this:
let test = await client.search({
index: 'test',
type: 'doc',
body: {
query: {
bool: {
must: [
{
match: {
title: 'something',
}
},
{
match: {
desc: 'some Qualifications',
}
}
]
}
}
}
});
I have two files, how can I pass the value to variable?
sample.js:
module.exports = {
content: [
{
table: {
body: [
[
{ text: address, alignment: 'center'}
]
}
}
}
app.js:
var sample = require('sample');
How to pass the address into the sample object?
You want to export a function that returns an object:
module.exports = function (address) {
return {
content: [
{
table: {
body: [
{
text: address,
alignment: 'center'
}
]
}
}
]
}
};
Now you can fill the values:
var sample = require("./sample");
console.log(sample("fooAddress"));
function getContent(adress) {
return content: [
{
table: {
body: [
[
{ text: address, alignment: 'center'}
]
}
}
}
module.exports = getContent;
app.js:
var sample = require('./sample')(adress);
Try this:
module.exports = (address) => {
return {
content: [
{
table: {
body: [
{text: address, alignment: 'center'}
]
}
}
]
}
}
var sample = require('sample')('The address');
You can make module.exports to be a function:
sample.js
module.exports = (address) => { return { content: [
{
table: {
body: [
{text: address, alignment: 'center'}
]
}
}
] };}
app.js
var sample = require('sample')('your address parameter');
I am implementing a search feature with react and relay.
Below is my schema.js
var { nodeInterface, nodeField } = nodeDefinitions(
(globalId) => {
var { type, id } = fromGlobalId(globalId);
if (type === 'User') {
return getUser(id);
}else if (type === 'Post') {
return getPost(id);
}else if (type === 'Setting') {
return getSetting(id);
}
return null;
},
(obj) => {
if (obj instanceof User) {
return userType;
}else if (obj instanceof Post) {
return postType;
}else if (obj instanceof Setting) {
return settingType;
}
return null;
}
);
var postType = new GraphQLObjectType({
name: 'Post',
fields: {
_id: {
type: new GraphQLNonNull(GraphQLID)
},
createdAt: {
type: GraphQLString
},
id: globalIdField('Post'),
title: {
type: GraphQLString
},
color: {
type: GraphQLString
},
userId: globalIdField('User'),
username: {
type: GraphQLString,
resolve: (post) => getUserById(post.userId),
},
content: {
type: GraphQLString
},
images: {
type: postImageType,
description: "Post's main image links"
}
},
interfaces: [nodeInterface]
});
const {
connectionType: postConnection,
} = connectionDefinitions({name: 'Post', nodeType: postType});
var settingType = new GraphQLObjectType({
name: 'Setting',
fields: {
_id: {
type: new GraphQLNonNull(GraphQLID)
},
id: globalIdField('Setting'),
amount: {
type: GraphQLString
},
all_posts: {
type: postConnection,
args: {
...connectionArgs,
query: {type: GraphQLString}
},
resolve: (rootValue, args) => connectionFromPromisedArray(
getAllPosts(rootValue, args),
args
),
},
},
interfaces: [nodeInterface]
});
var Root = new GraphQLObjectType({
name: 'Root',
fields: () => ({
node: nodeField,
setting: {
type: settingType,
args: {
...connectionArgs,
currency: {type: GraphQLString}
},
resolve: (rootValue, args) => {
return getSetting(args.currency).then(function(data){
return data[0];
}).then(null,function(err){
return err;
});
}
},
})
});
Below is my database.js
export function getAllPosts(params,args) {
let findTitle = {};
let findContent = {};
if (args.query) {
findTitle.title = new RegExp(args.query, 'i');
findContent.content = new RegExp(args.query, 'i');
}
console.log("getAllPosts",args)
return new Promise((resolve, reject) => {
Post.find({$or: [findTitle,findContent]}).sort({createdAt: 'descending'}).exec({}, function(err, posts) {
if (err) {
resolve({})
} else {
resolve(posts)
}
});
})
}
Now I want to fetch all posts by $query variable
So in view I wrote like this
import React, { Component } from 'react';
import Relay from 'react-relay';
class BlogList extends Component {
constructor(props) {
super(props);
this.state = {
query: '',
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(){
this.props.relay.setVariables({query: this.state.query});
}
render() {
return (
<div className="input-group col-md-12">
<input type="text" onChange={this.handleChange.bind(this,"query")} value={this.state.query} name="query" placeholder="Enter Title or content"/><br/>
<span className="input-group-btn">
<button type="button" onClick={this.handleSubmit} className="btn btn-info btn-lg">
<i className="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
)
}
};
export default Relay.createContainer(BlogList, {
initialVariables: {
query: ''
},
fragments: {
viewer: () => Relay.QL`
fragment on Setting {
id,
all_posts(first: 10000000,query: $query) {
edges {
node {
id,
_id,
title,
content,
createdAt,
username,
color,
images{
full
}
}
}
}
}
`,
},
});
And in routes I have
const SettingQueries = {
viewer: () => Relay.QL`query{
setting(currency: "USD")
}`,
}
export default [{
path: '/',
component: App,
queries: UserQueries,PostQueries,SettingQueries,
indexRoute: {
component: IndexBody,
},
childRoutes: [
,{
path: 'settings',
component: Setting,
queries: SettingQueries,
}]
}]
Things are working on /graphql as
but when I search from website it generates error in response
{
"data": {
"node": null
},
"errors": [
{
"message": "Abstract type Node must resolve to an Object type at runtime for field Root.node with value \"\",received \"null\".",
"locations": [
{
"line": 2,
"column": 3
}
]
}
]
}
as my web-browser is sending requests as below
Please suggest me what am I missing?
Also If I need to add some additional information please let me know.
The problem might be in your nodeDefinitions() function. First callback, also named idFetcher must return a single object. However, i see in your definition that you return a collection
var { nodeInterface, nodeField } = nodeDefinitions(
(globalId) => {
var { type, id } = fromGlobalId(globalId);
...
}else if (type === 'Post') {
return getPosts(); // this should be getPost(id)
}
);
And thats why your next callback, known as typeResolver fails and returns you a null.
var { nodeInterface, nodeField } = nodeDefinitions(
...
(obj) => {
...
// here you get Promise/Collection instead of single Post instance, therefore condition failed
}else if (obj instanceof Post) {
return postType;
}
return null;
}
);
LordDave's answer revealed one problem in your code. As you commented in his answer, all_posts field of settingType was not working.
If you used mongoose library in your DB code, I see a problem with your query:
Post.find({$or: [findTitle,findContent]}).sort({createdAt: 'descending'}).exec({}, function(err, posts) {
if (err) {
resolve({})
} else {
resolve(posts)
}
});
Based on documentation of exec, change your query to
return Post.find({$or: [findTitle,findContent]}).sort({createdAt: 'descending'}).exec(function(err, posts) {
if (err) {
resolve({})
} else {
resolve(posts)
}
});
As exec returns a promise, you can even do
return Post.find({$or: [findTitle,findContent]}).sort({createdAt: 'descending'}).exec();
Finally I got it working by creating a new type 'postList' and defined it as below
var { nodeInterface, nodeField } = nodeDefinitions(
(globalId) => {
var { type, id } = fromGlobalId(globalId);
if (type === 'User') {
return getUser(id);
}else if (type==='postList') {
return getpostList(id);
} else{
return null;
}
},
(obj) => {
if (obj instanceof User) {
return userType;
}else if (obj instanceof postList) {
return postListType;
}else{
return null;
}
}
);
In database.js
class postList {}
postList.id = "Post_id";
export {postList}
export function getpostList(id) {
return new postList
}
and under root fields as below
var postListType = new GraphQLObjectType({
name: 'postList',
description: 'List of posts',
 fields: () => ({
 id: globalIdField('postList'),
 posts: {
 type: postConnection,
 description: 'List of posts',
 args: {
...connectionArgs,
query: {type: GraphQLString}
},
 resolve: (_, args) => connectionFromPromisedArray(getAllPosts(_,args), args),
 },
}),
interfaces: [nodeInterface],
});
var Root = new GraphQLObjectType({
name: 'Root',
fields: () => ({
node: nodeField,
postList: {
type: postListType,
resolve:(rootValue)=> {
return getpostList()
}
},
})
});
I ran into this issue when I was using an InterfaceType and checked for the InterfaceType before the specialized ObjectType in the if-elseif-else of my TypeResolver
I want to display predictive text in search field, value for predictive text which comes from server. Here is my code so far:
View:
Ext.define('MyApp.view.AutoSearch', {
extend: 'Ext.dataview.List',
alias : 'widget.mainPanel',
config: {
store : 'AutoSearchStore',
itemTpl: '<div class="myWord">'+
'<div>Word is --<b>{name}</b>--- after search!!!</div>' +
'</div>',
emptyText: '<div class="myWord">No Matching Words</div>',
items: [
{
xtype: 'toolbar',
docked: 'top',
items: [
{
xtype: 'searchfield',
placeHolder: 'Search...',
itemId: 'searchBox'
}
]
}
]
}
});
Store:
Ext.define('MyApp.store.AutoSearchStore',{
extend: 'Ext.data.Store',
config:
{
model: 'MyApp.model.AutoSearchModel',
autoLoad:true,
id:'Contacts',
proxy:
{
type: 'ajax',
url: 'http://alucio.com.np/trunk/dev/sillydic/admin/api/word/categories/SDSILLYTOKEN/650773253e7f157a93c53d47a866204dedc7c363',
reader:
{
rootProperty:''
}
}
}
});
Model:
Ext.define('MyApp.model.AutoSearchModel', {
extend: 'Ext.data.Model',
requires: ['MyApp.model.AutoSearchModelMenu'],
config: {
fields: [
{name:'data', mapping: 'data'},
{name: 'name'},
],
},
});
and
Ext.define('MyApp.model.AutoSearchModelMenu', {
extend: 'Ext.data.Model',
config: {
fields: [
'name',
],
belongsTo: "MyApp.model.AutoSearchModel"
}
});
Controller:
Ext.define('MyApp.controller.SearchAutoComplete', {
extend : 'Ext.app.Controller',
config: {
profile: Ext.os.deviceType.toLowerCase(),
stores : ['MyApp.store.AutoSearchStore'],
models : ['MyApp.model.AutoSearchModel'],
refs: {
myContainer: 'mainPanel'
},
control: {
'mainPanel': {
activate: 'onActivate'
},
'mainPanel searchfield[itemId=searchBox]' : {
clearicontap : 'onClearSearch',
keyup: 'onSearchKeyUp'
}
}
},
onActivate: function() {
console.log('Main container is active--Search');
},
onSearchKeyUp: function(searchField) {
queryString = searchField.getValue();
console.log(this,'Please search by: ' + queryString);
var store = Ext.getStore('AutoSearchStore');
store.clearFilter();
if(queryString){
var thisRegEx = new RegExp(queryString, "i");
store.filterBy(function(record) {
if (thisRegEx.test(record.get('name'))) {
return true;
};
return false;
});
}
},
onClearSearch: function() {
console.log('Clear icon is tapped');
var store = Ext.getStore('AutoSearchStore');
store.clearFilter();
},
init: function() {
console.log('Controller initialized for SearchAutoComplete');
}
});
Json Data Looks Like:
"data":[
{
"name":"paint",
"author":"admin",
"word_id":"1",
"category":"Business",
"is_favourite":"yesStar"
},
{
"name":"abacus",
"author":"admin",
"word_id":"2",
"category":"Education",
"is_favourite":"yesStar"
},
{
"name":"abate",
"author":"admin",
"word_id":"3",
"category":"Education",
"is_favourite":"noStar"
},
{
"name":"testing adsf",
"author":"admin",
"word_id":"7",
"category":"Education",
"is_favourite":"noStar"
},
{
"name":"sprite",
"author":"admin",
"word_id":"6",
"category":"Business",
"is_favourite":"noStar"
},
{
"name":"newword",
"author":"admin",
"word_id":"8",
"category":"Architecture",
"is_favourite":"noStar"
}
]
})
If I type "A", then it displays No Matching Words, but I have words from "A" on json coming from server. How to solve this problem?
Any idea!
Code Sources Link
I don't know why you are using two models but just one thing you need to specify in AutoSearchStore :
reader:
{
rootProperty:'data'
}
instead of
reader:
{
rootProperty:''
}
to get the expected results in the list.
Hope this will be helpful :)