Vue querying from backend - vuetify.js

I'm learning fronted with my friend who's learning backend. He got me endpoint's with filters like this:
to use searchbar with categories+sortyby+pages
I've got it to work by hardcoding terrible function to work just for now
getArticlesPage(search,category,sort){
if ((search=='' || search==undefined) && (category=='' ||category==undefined) && (sort==''|| sort==undefined)){//on initialize
axios.get(this.address+'knowledge/articles?page='+this.pickedPage)
.then((result)=>{
this.articles=result.data
console.log(this.articles)
})
.catch(error=> {
if (error) {
// console.log('error');
// console.log(error);
// console.log(error.response);
}
})
}else if(search!=''&& (category==''|| category==undefined) && (sort==''|| sort==undefined)){//if user search for something without sort and category
console.log(this.address+'knowledge/articles?page='+this.pickedPage+'&'+search)
axios.get(this.address+'knowledge/articles?page='+this.pickedPage+'&search='+search)
.then((result)=>{
this.articles=result.data
console.log(this.articles)
})
.catch(error=> {
if (error) {
// console.log('error');
// console.log(error);
// console.log(error.response);
}
})
}
else if(search!=''&& category!='' && (sort==''|| sort==undefined)){//if user search for something with category picked on, without sorting
console.log(this.address+'knowledge/articles?page='+this.pickedPage+'&search='+search)
axios.get(this.address+'knowledge/articles?page='+this.pickedPage+'&search='+search)
.then((result)=>{
this.articles=result.data
console.log(this.articles)
})
.catch(error=> {
if (error) {
// console.log('error');
// console.log(error);
// console.log(error.response);
}
})
}
else if((search=='' || search==undefined)&& category!='' && sort!=''){//if user changes just category and sort
console.log(this.address+'knowledge/articles?page='+this.pickedPage+'&category='+this.pickedCategory)
axios.get(this.address+'knowledge/articles?page='+this.pickedPage+'&category='+this.pickedCategory)
.then((result)=>{
this.articles=result.data
console.log(this.articles)
})
.catch(error=> {
if (error) {
// console.log('error');
// console.log(error);
// console.log(error.response);
}
})
}
else if(search!=''&& (category==''|| category==undefined) && sort!=''){//if user search for something with sort on
console.log(this.address+'knowledge/articles?page='+this.pickedPage+'&search='+search+sort)
axios.get(this.address+'knowledge/articles?page='+this.pickedPage+'&search='+search+sort)
.then((result)=>{
this.articles=result.data
console.log(this.articles)
})
.catch(error=> {
if (error) {
// console.log('error');
// console.log(error);
// console.log(error.response);
}
})
}
else if(search!=''&& category!='' && sort!=''){//if user search for something with sort and category on
console.log(this.address+'knowledge/articles?page='+this.pickedPage+'&search='+search+sort+'&category='+this.pickedCategory)
axios.get(this.address+'knowledge/articles?page='+this.pickedPage+'&search='+search+sort+'&category='+this.pickedCategory)
.then((result)=>{
this.articles=result.data
console.log(this.articles)
})
.catch(error=> {
if (error) {
// console.log('error');
// console.log(error);
// console.log(error.response);
}
})
}
else if((search=='' || search==undefined) && (category=='' ||category==undefined) && sort!=''){//if user changes only sorting
console.log(this.address+'knowledge/articles?page='+this.pickedPage+sort)
axios.get(this.address+'knowledge/articles?page='+this.pickedPage+sort)
.then((result)=>{
this.articles=result.data
console.log(this.articles)
})
.catch(error=> {
if (error) {
// console.log('error');
// console.log(error);
// console.log(error.response);
}
})
}
else if ((search=='' || search==undefined) && category!='' && (sort==''|| sort==undefined)){//on initialize
console.log(this.address+'knowledge/articles?page='+this.pickedPage+'&category='+this.pickedCategory)
axios.get(this.address+'knowledge/articles?page='+this.pickedPage+'&category='+this.pickedCategory)
.then((result)=>{
this.articles=result.data
console.log(this.articles)
})
.catch(error=> {
if (error) {
// console.log('error');
// console.log(error);
// console.log(error.response);
}
})
}
else console.log('whoopsie')
},
+few watchers on sort/category for them to work correctly
It works, but i know it's a terrible way, and it will scale up dramatically if we add more filters, so could You experts please help me by showing proper way to do it?
Can't find any useful documentation/page about it, and i know there has to be many, because its a popular topic...
Would be best if it's in pure vue, but I can install any package if needed.
I don't know how much is it changing, but I'm using Vue router. With this function, I can't show user links he's using, but I really don't know conception of it (I mean, should I, or better not to?)

Related

DynamoDB.putitem not adding paramaters to DynamoDB table?

My lambda function uses the method
ddb.putItem(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log("SUBMITTED DATA"); // successful response
});
with my params being correctly formatted to my table. No error is shown in my logs, however "SUBMITTED DATA" does not appear in the logs either, and the data is not put into my DynamoDB table. Any idea on what might be causing this problem? Heres my complete function:
const TrackHabitIntentHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'TrackHabitIntent';
},
handle(handlerInput) {
ddb.putItem(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log("SUBMITTED DATA"); // successful response
});
const speechText = "That's awesome! I'll add today to your streak of 4 days";
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(speechText)
.withSimpleCard('Hello World', speechText)
.getResponse();
}};
exports.handler = function (event, context) {
if (!skill) {
skill = Alexa.SkillBuilders.custom()
.addRequestHandlers(
LaunchRequestHandler,
HelpIntentHandler,
HelpMeIntentHandler,
TrackHabitIntentHandler,
NewHabitIntentHandler,
CancelAndStopIntentHandler,
SessionEndedRequestHandler,
)
.addErrorHandlers(ErrorHandler)
.create();
}
return response;
};
Thanks
Please check this code to add data in dynamoDB that can help you.
let putParams = {
TableName: tableName,
Item: {
'Id': {
S: Id
},
'name': {
S: name
}
},
ConditionExpression: 'attribute_exists(Id)'
};
dynamoDb.putItem(putParams, function (err, data) {
if (err) {
console.log('failure:put data from Dynamo error', err);
reject(err);
} else {
console.log('success:put data from Dynamo data');
resolve(data);
}
});

React Displaying List of Items from Ajax request

I am learning React and I am trying to display a list of users from and ajax call. I am getting an unexpected token error from CodePen when I add the line
export default Users;
When I remove the line there are no more errors but the list of users is not being displayed.
My code:
function GetUsers(project){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
console.log(data);
callback(null, data);
},
error: function (error) {
console.log(data);
callback(error, {});
}
});
}
function UserList(users) {
const userItems = users.map((user) =>
<ul>
<li>
{ user.name }
</li>
<li>
{ user.email }
</li>
<li>
{ user.phone}
</li>
</ul>
);
return (userItems);
}
class Users extends Component {
componentDidMount() {
GetUsers(null, function (err, data) {
if (err)
{
console.log(err);
}// do something
this.setState({ users: data })
}.bind(this))
}
render() {
return(
<UserList user = {this.state.users} />
);
}
}
if (document.getElementById('root')) {
ReactDOM.render(<Users />, document.getElementById('root'));
}
Here is my code.
Thank you for any and all help!
Problem 1 in AJAX call
function GetUsers(project){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
console.log(data);
callback(null, data);
},
error: function (error) {
console.log(data);
callback(error, {});
}
});
}
$.ajax is asynchronous call, that means it doesn't returns directly any value (how it could if it is fetching the results from the internet) it Just creates another function which will call success and error when completed.
That's why we need to wrap it with callbacks
function GetUsers(project, resolve = () => {}, reject = () => {}) {
}
Problem 2 in mount
componentDidMount() {
GetUsers(null, function (err, data) {
if (err)
{
console.log(err);
}// do something
this.setState({ users: data })
}.bind(this))
}
This code is completely wrong, it has even syntax error so not worth to discuss it in details.
We need to call our new function and pass success callback for mutating the state
GetUsers(null, users => {
this.setState({ users });
});
In this way we will call GetUsers wait for it's results and only after that we will mutate the state with new result
3 problem in component creation
React component's don't have state by default, you need to infer the state from constructor so we need to change initialization to
constructor(props) {
super(props);
this.state = {
users: false
};
}
otherwise you will get Cannot call setState of undefined as state is not automatically created for performance purposes and all components are Pure by default.
I have created a working sandbox here
in
function GetUsers(project){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
return data;
},
error: function (error) {
console.log(error);
return {};
}
});
}
--
success: function (data) {
return data;
}
doesn't do what you think it does. return data isn't really returning the data... anywhere.
You need to have a callback.
function GetUsers(project, callback){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
callback(null, data)
},
error: function (error) {
callback(error, {})
}
});
}
class Users extends Component {
componentDidMount() {
GetUsers(null, function (err, data) {
if (err) // do something
this.setState({ users: data })
}.bind(this))
}
render() {
return(
<UserList user = {this.state.users} />
);
}
}
you can also Promise-ify things to simplify the logic

Service worker should not cache the whole page

I register '/' (route) .css and .js file as URL that should be cached at first.
But after that I realize that it cached the whole page, which means I don't see any update on my view, event there is an update on database.
So I change it only cache my .css and .js file not route ('/') anymore , I expected that's the problem.
But after awhile, the same problem still occurred. I check on my console it did cache the whole page again, even though my Service Worker file already change like this:
var CACHE_NAME = 'cache-v2';
var urlsToCache = [
'/assets/css/app.css',
'/assets/js/main.js',
'/assets/js/other.js'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('activate', function(e) {
console.log('[ServiceWorker] Activate');
e.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (key !== CACHE_NAME) {
console.log('[ServiceWorker] Removing old cache', key);
return caches.delete(key);
}
}));
})
);
return self.clients.claim();
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
var fetchRequest = event.request.clone();
return fetch(fetchRequest).then(
function(response) {
if(!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
var responseToCache = response.clone();
caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(event.request, responseToCache);
});
return response;
}
);
})
);
});
in case anyone has the same problem,
here is what i should change
self.addEventListener('fetch', function(e) {
console.log('[ServiceWorker] Fetch', e.request.url);
e.respondWith(
caches.match(e.request).then(function(response) {
return response || fetch(e.request);
})
);
});
so my previous fetch looks like the problem

Issue with Promise

I got a small problem with my function below. The Promise.map doesn't wait for Folder.create to be finished and iterate through the next value.
Promise.map(name, function(na){
return fs.stat(na.url, function(err, stats){
if (typeof stats === 'undefined'){
console.log("file doesn't exist");
return Folder.create(na).then(function(fd){
return mkdirp(root + product.url).then(function(){
console.log("Folder Created");
return null;
});
}, function(err){
console.log(err);
return reject({message: "Error when creating the folder"});
});
}
});
}).then(function(){
console.log('Iteration Done');
return resolve({message: "Folder Created!"});
});
// I GOT :
//file doesn't exist
//file doesn't exist
//file doesn't exist
//Iteration Done
//file doesn't exist
//file doesn't exist
//file doesn't exist
//Iteration Done
//Folder Created
//Folder Created
//Folder Created
//Folder Created
//Folder Created
//Folder Created
There are a couple issues here:
Promise.map() runs the operations for each array element in parallel, not serially. If you want them run serially, you can pass {concurrency: 1} as an option to Promise.map() or use Promise.mapSeries().
fs.stat() does not return a promise so your main callback to Promise.map() isn't returning a promise so the whole Promise.map() infrastructure does not know how to wait for any of your results. You can promisify fs.stat() to solve that issue.
You appear to be using an anti-pattern with your resolve() and reject() calls in here. You don't show the outer definition where those come from, but you should be just using the promise returned from Promise.map() rather than doing that.
Here's how they can successfully be run in parallel:
var fs = Promise.promisifyAll(require('fs'));
Promise.map(name, function(na){
return fs.statAsync(na.url).then(function(err, stats){
if (typeof stats === 'undefined'){
console.log("file doesn't exist");
return Folder.create(na).then(function(fd){
return mkdirp(root + product.url).then(function(){
console.log("Folder Created");
return null;
});
}, function(err){
console.log(err);
return Promise.reject({message: "Error when creating the folder"});
});
}
});
}).then(function(){
console.log('Iteration Done');
return ({message: "Folder Created!"});
});
If you wanted to run your operations serially with Bluebird, you could pass {concurrency: 1} to Promise.map():
Promise.map(name, fn, {concurrency: 1}).then(...);
Or use:
Promise.mapSeries(name, fn).then(...)
fs.stat is a callback type function and thus, does not return a Promise. You should modify your code to be something like this
// This might not work directly. I haven't tried to run it
Promise.map(name, function(na) {
return new Promise(function(resolve, reject) {
fs.stat(na.url, function(err, stats) {
if (typeof stats === 'undefined') {
console.log("file doesn't exist");
Folder.create(na).then(function(fd) {
return mkdirp(root + product.url);
}).then(function() {
console.log("Folder Created");
resolve();
}).catch(function(err) {
console.log(err);
reject({
message: "Error when creating the folder"
});
});
} else {
resolve();
}
});
});
}).then(function() {
console.log('Iteration Done');
return {
message: "Folder Created!"
};
});

Cannot return the value from my function

I could not return the value from the function, I have no problem with my sql it works fine, I just can't return the result value and pass it to res variable.
io.on('connection', function (socket) {
socket.on('getdetails', function (data) {
var res = getdatatodb(data.id);
console.log("result",res);
});
});
});
function getdatatodb(id){
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
var options = {sql: ".....",nestTables: true };
connection.query(options,function(err, results) {
if(err){
console.log(err);
}
return results;
});
});
}
Thank you in advance.

Resources