Algolia + Laravel backend API + nuxtJS - javascript

I have a Laravel 8 backend API and a completely separate NuxtJS frontend. I have integrated Algolia into the backend API. I have a nice adapter and service and I can search my index.
Now, I am not interested in using scout because I don't like what it is doing and how it works and that's not the problem so I would like to leave it out of the discussion.
So I've made search work on the frontend with Vuetify autocomplete but I decided to use VueInstant search as this is supposed to save me some work when it comes to integrating query suggestions.
Before I can even get query suggestion I need to get the basic search working with Vue Instant Search.
GOAL
I want to have a VueInstant Search with the backend search client.
WHAT I HAVE SO FAR
THAT IS WITHOUT QUERY SUGGESTIONS JUST THE BASIC SEARCH WITH VUEINSTANT SEARCH
I have backend code that searches my index. I have the frontend code that creates a new connection to my backend (don't worry about how it looks like I just need to get this to work first and then I will invest the time to refactor it):
customSearchClient () {
const that = this
return {
search(requests) {
return that.fetchContainers({ criteria: { query: 'super' }, updateStore: false }).then(response => {
// console.log({ response }, typeof response)
// return response.data.hits
return { results: response.data }
// return response
// return response.data.hits
})
}
}
}
And this is my code for the form:
<ais-instant-search index-name="containers-index" :search-client="customSearchClient()" >
<ais-search-box />
<ais-hits>
<template slot="item" slot-scope="{ item }">
<h1><ais-highlight :hit="item" attribute="name" /></h1>
<p><ais-highlight :hit="item" attribute="description" /></p>
</template>
</ais-hits>
</ais-instant-search>
PROBLEMS
I can get the searchbox to show and query if I remove ais-hits tags. As soon as I add them I get weird errors depending on how I format my response from the backend. I just try to pass it as it is.
I went through some debugging and tried to wrap this into various wrappers as they seem to be missing but eventually it always breaks, for example:
algoliasearch.helper.js?ea40:1334 Uncaught (in promise) TypeError: content.results.slice is not a function at AlgoliaSearchHelper._dispatchAlgoliaResponse (algoliasearch.helper.js?ea40:1334:1)
And that is the Algolia code that breaks.
this._currentNbQueries -= (queryId - this._lastQueryIdReceived);
this._lastQueryIdReceived = queryId;
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
var results = content.results.slice();
states.forEach(function(s) {
var state = s.state;
var queriesCount = s.queriesCount;
var helper = s.helper;
var specificResults = results.splice(0, queriesCount);
var formattedResponse = helper.lastResults = new SearchResults(state, specificResults);
SUMAMRY
The ideal solution would be to not to use this InstantSearch thing but I have no clue how to manage more than one index on the server side.
Or am I completely wrong about all of that? Anyone can advise?

Related

Display data from database (using mongodb) in hbs/html file Node.Js

I started studying node.js, and now I'm trying to do a "Todo-App".
I'm trying to find the best way to transfer data from my database (using mongodb) into my hbs files, so I could display it.
From the server.js -> server to the hbs -> client (correct to me if I'm wrong please, by assuming that server.js is the server of course and the hbs file is the client)
So, I succeeded to do it by passing an array.
but when I'm trying to display in html desing, it just looking bad.
The code:
app.get('/allTasks',(req,res)=>{ //get (go to) the allTasks (hbs file)
Todo.find().then((todos) => {
console.log(todos);
var arrayOfTodos = [];
todos.forEach(function(element){
console.log("\n\n\n\n\n elemnt details: ",element.text + "\n",element.completed+"\n");
arrayOfTodos.push(element.text,element.completed);
});
res.render("allTasks.hbs", {
pageTitle: "Your tasks: ",
todos: arrayOfTodos
});
});
});
The result is:
You can see a picture
As you can see, its just looking bad... cause it just display an array,
an I want to display each task seperately.
Any tips?
Thanks a lot,
Sagiv
Instead of using push just do:
Todo.find().toArray(function(err, result){
arrayOfTodos = result;
})
Once you have your array, the design got nothing to do with mongodb. You will need to learn how to use your render technology. You need to touch your html template, so you should start by posting that.
The problem solved.
I just had to learn how to handle the data in the hbs side.
so the code is: (in hbs)
{{#each todos}}
{{missionNumber}} <br>
{{text}}<br>
completed = {{completed}}<br><br>
{{/each}}
as you can see, the each is a loop , that pass on the todos parameter (my array)
and i just have to display the data in the way i want it to be displayed.
thanks for your help.

Userless Authentication Foursquare API "Missing access credentials" - 400 error

Bit of a weird one. I'm building a React js app interacting with the Foursquare API, mainly just to learn about React js and APIs.
I'm using Foursquare to get Venue information, that works fine. I also want to use it to get venue photos which is where the fun starts.
The method that processes the original call to venues is as follows. I'm just putting this here for to provide a control as this works fine. It returns the venue information which i process within the app with no problem:
getVenues: (searchTerm) => {
const urlToFetch =
${urlExplore}${searchTerm}&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20180602;
return fetch(urlToFetch).then( response => {
return response.json();
}).then( jsonResponse => {
if (jsonResponse.response.groups[0].items) {
return jsonResponse.response.groups[0].items.map(item => (
{
id: item.venue.id,
name: item.venue.name,
// blah
}
));
} else {
return [];
}
})
}
So far, so good, it works fine. However, when I try the same approach accessing the photos endpoint, the method returns a series of objects containing meta which says:
​ code: 400
​​ errorDetail: "Missing access credentials. See
https://developer.foursquare.com/docs/api/configuration/authentication for
details."
​​errorType: "invalid_auth"
Suffice to say the information at the link provided doesn't actually give much help :-(
The method I'm using to get the photo information is:
getVenuePhotos: (venueId) => {
const fetchPhotosURL = `${urlPhotos}${venueId}/photos&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20180602`;
return fetch(fetchPhotosURL).then( response => {
return response.json();
}).then( jsonResponse => {
console.log(jsonResponse);
//blah - removed to save space - see method above, it's pretty much the same
})
}
...both are stored in an object in a separate file which the react component imports.
The url vars resolve as follows (asterisks are my addition):
fetchVenuesURL: https://api.foursquare.com/v2/venues/explore?near=london&limit=10&client_id=**** &client_secret=****&v=20180602
fetchPhotosURL: https://api.foursquare.com/v2/venues/4ac518eff964a52064ad20e3/photos&limit=10&client_id=**** &client_secret=****&v=20180602
Does anyone have any idea why this might be happening?
thanks in advance
I think there is a typo in your URL.
Replace
${urlPhotos}${venueId}/photos&limit=10&client...
with
${urlPhotos}${venueId}/photos?limit=10&client...

How to retrieve both caller-name and carrier from Twilio in node.js?

Im having problems working with the twilio-api for node.
i wrote this code:
let typeArray = ['caller-name','carrier'];
this.client.phoneNumbers(phoneNumberToCheck).get({
type: typeArray
}, (error, number) => {
// working on the number data results
// ...
});
The problem is that i dont get ANY of them(carrier/caller-name) - although passing array to argument 'type' is the way to do it in other languages(php,c#..) but it doesnt work on node.js, instead i get this:
// -> get
{
"caller_name":null,
"country_code":"US",
"phone_number":"+123456789",
"national_format":"(248) 123-456",
"carrier":null,
"add_ons":null,
"url":"https://lookups.twilio.com/v1/PhoneNumbers/+123456789",
"callerName":null,
"countryCode":"US",
"phoneNumber":"+123456789",
"nationalFormat":"(248) 123-456",
"addOns":null
}
note: if i send each one separately (only carrier or only caller-name) - i get the partial information for each.
how can i get both in one request in node.js?
Twilio developer evangelist here.
You should be calling the Lookups API in Node this way:
client.lookups.phoneNumbers.get(phoneNumber)
.fetch({
type: ['carrier', 'caller-name']
},
function(err, result) {
// do something
}
)
The docs are a little lacking in Node.js on the Lookups documentation and I will raise that with the team.

Meteor Query Filtering with Search Source

I have successfully implemented The basic search source setup as outlined in the setup on the Github README for Arunoda's Meteor Package. I am now attempting to add filters to work with the search. These filter options are found on a separate search page and consist of checkboxes that can be checked on or off. I have come up with the following server method I call with the event handler.
searchFilter: function (option) {
var selectorCity = {
city: 'Queens'
};
var selectorCategory = {
category: 'Apparel'
};
console.log(selectorCategory);
var query = Listing.find({ $and:[ selectorCategory, selectorCity ] }).fetch();
console.log(query);
return query;
}
The query executes successfully and finds and logs (in the console) the single document I am testing with. It however does not change the output on the page to that query. I believe I may have to use SearchSource's getData() method but I am not sure how.
What options are available for rendering the content on to the page?

Breeze EntityManager.executeQuery with expand - httpResponse data does not match result data?

I'm working on a web app that uses Breeze and Knockout. I have the following function:
function getArticle(id, articleObservable) {
var query = EntityQuery.from('KbArticles')
.where("articleId", "==", id)
.expand("KbArticleType, KbSubject, KbArticleTags");
return manager.executeQuery(query)
.then(querySucceeded)
.fail(queryFailed);
function querySucceeded(data) {
if (articleObservable) {
articleObservable(data.results[0]);
}
log('Retrieved [Article] from remote data source', data.results.length, true);
}
}
A 1 to many relationship exists between the KbArticles entity and the KbArticleTags entity. The goal of this function is to fetch a specific article and the list of tags associated with the article. The function executes successfully (and I DO get data for the other 2 expanded entities - they are 1 to 1), however, I get an empty array for the KbArticleTags in data.results. Interestingly, the tags are populated in data.httpResponse:
So, it appears that the data is coming over the wire, but it's not making it to the results in the querySucceeded function. I tried to step through the breeze code to determine how the httpResponse is mapped to the result, but got lost fairly quickly (I'm a javascript newb). Does anyone have any troubleshooting tips for figuring out why the expanded entity doesn't show in the results, but is returned in the httpResponse? Or am I trying to do something that isn't supported?
Ok, so for whatever reason (I probably deleted it one day while testing and didn't add it back), the navigation property (in my Entity Framework diagram) was missing on the KbArticleTag entity:
All I had to do was add that back and everything is working as expected.

Categories

Resources