I use
app.configure( function(){
app.use(express.static(__dirname, '/'));
});
then I figured out it's the old version. Then I used this,
var env = process.env.NODE_ENV || 'development';
if ('development' == env) {
app.use(express.static(__dirname, '/'));
}
but it still give me errors. My whole code is below.
var express = require('express'),
app = express();
var env = process.env.NODE_ENV || 'development';
if ('development' == env) {
app.use(express.static(__dirname, '/'));
}
app.get('/people/:id', function(req, res){`
var customerId = parseInt(req.params.id);
var data = {};
for(var i = 0; i < people.length; i++){
if(people[i].id === customerId){
data = people[i];
break;
}
}
res.json(data);
});
app.get('/people', function(req, res){
res.json(people);
});
app.lisen(8080);
console.log('Listening on express port 8080');
var people = [
{id: 1, name: 'John', city: 'Lisbon', gender: 'male', total: '515.561',
orders: [
{id: 1, product: 'Shoes', total: '100'}
]
},
{id: 2, name:'Abbie', city:'Orlando', gender:'female', total:'3445.34',
orders: [
{id: 2, product: 'Shoes', total: '200.561'}
]
},
{id: 3, name:'Will', city:'Houston', gender:'female', total:'98754.00',
orders: [
{id: 1, product: 'Shoes', total: '300.561'},
{id: 3, product: 'Shoes', total: '330.561'}
]
},
{id: 4, name:'Jim', city:'Paris', gender:'male', total:'15.26',
orders: [
{id: 4, product: 'Shoes', total: '400.561'}
]
},
{id: 5, name:'Bryan', city:'Lisbon', gender:'male', total:'515.561',
orders: [
{id: 5, product: 'Shoes', total: '500.561'}
]
},
{id: 6, name:'Agulera', city:'Orlando', gender:'female', total:'3445.34',
orders: [
{id: 6, product: 'Shoes', total: '600.561'}
]
},
{id: 7, name:'Christeen', city:'Houston', gender:'female', total:'98754.00',
orders: [
{id: 7, product: 'Shoes', total: '700.561'}
]
},
{id: 8, name:'Matt', city:'Paris', gender:'male',total:'15.26',
orders: [
{id: 8, product: 'Shoes', total: '800.561'}
]
}
];
I'm quite new to express and I'm doing this by watching a video. so I want to configure it properly and run it. Please help me with this.
spelling error
app.lisen(8080);
--->
app.listen(8080);
second...
global variables are bad strategy, put the var people as a local variable of app:
http://expressjs.com/api.html#app.locals
app.locals.people = "put the people data here";
Lastly, you should put responses and relevant http error codes to diagnose where there are errors:
for example.....
var yes = "yes";
if ( yes !== data.answer) {
console.log(err);
res.status(401).send(err + "error, you do not have authorized access to this data"); }
else {
console.log("success! You are authorized!")
res.status(200).send(data);
};
Sends back json object data and "ok" status code if condition is met;
status codes:
http://www.w3.org/Protocols/HTTP/HTRESP.html
Related
I am trying to use multiple ramda functions on this example:
const data = {
"tableItems": [
{
"id": 1,
"name": "1",
"startingPoint": true,
"pageNumber": 15,
"nodes": [
100,
200
]
},
{
"id": 2,
"name": "2",
"startingPoint": true,
"pageNumber": 14,
"nodes": [
300,
400
]
}
],
"nodes": [
{
"id": 100,
"tableItemId": 1,
"content": "test"
},
{
"id": 200,
"tableItemId": 1,
"content": "test"
},
{
"id": 300,
"tableItemId": 2,
"content": "test"
},
{
"id": 400,
"tableItemId": 2,
"content": "test"
}
]
}
I am trying to create new JSON which should look like this where nodes array should be filled with another ramda function:
const newJSON = [
{
"id": "chapter-1",
"name": "2",
"nodes": []
},
{
"id": "chapter-2",
"name": "1",
"nodes": []
}
]
I started with:
let chapters = [];
let chapter;
const getChapters = R.pipe(
R.path(['tableItems']),
R.sortBy(R.prop('pageNumber')),
R.map((tableItem) => {
if(tableItem.startingPoint) {
chapter = {
id: `chapter-${chapters.length+1}`,
name: tableItem.name,
nodes: []
}
chapters.push(chapter);
}
return tableItem
})
)
But how to combine getNodes which needs access to the whole scope of data?
I tried pipe but something is not working.
Example:
const getNodes = R.pipe(
R.path(['nodes']),
R.map((node) => {
console.log(node)
})
)
R.pipe(
getChapters,
getNodes
)(data)
Any help would be appreciated.
We could write something like this, using Ramda:
const {pipe, sortBy, prop, filter, map, applySpec, identity, propEq, find, __, addIndex, assoc} = R
const transform = ({tableItems, nodes}) => pipe (
filter (prop ('startingPoint')),
sortBy (prop ('pageNumber')),
map (applySpec ({
name: prop('name'),
nodes: pipe (prop('nodes'), map (pipe (propEq ('id'), find (__, nodes))), filter (Boolean))
})),
addIndex (map) ((o, i) => assoc ('id', `chapter-${i + 1}`, o))
) (tableItems)
const data = {tableItems: [{id: 1, name: "1", startingPoint: true, pageNumber: 15, nodes: [100, 200]}, {id: 2, name: "2", startingPoint: true, pageNumber: 14, nodes: [300, 400]}], nodes: [{id: 100, tableItemId: 1, content: "test"}, {id: 200, tableItemId: 1, content: "test"}, {id: 300, tableItemId: 2, content: "test"}, {id: 400, tableItemId: 2, content: "test"}]}
console .log (transform (data))
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
First we filter the tableItems to include only those with startingPoint of true, then we sort the result by pageNumber. Then for each, we create name and nodes elements, based on the original data and on a function that maps the node values to the element in the initial nodes property. Finally, for each one, we add the chapter-# id element using addIndex (map).
This works, and is not horrible. It would take a fair bit of work to make this entirely point-free, I believe. And I don't find it worthwhile... especially because this Ramda version doesn't add anything to a simpler vanilla implementation:
const transform = ({tableItems, nodes}) =>
tableItems
.filter (x => x .startingPoint)
.sort (({pageNumber: a}, {pageNumber: b}) => a - b)
.map (({name, nodes: ns}, i) => ({
id: `chapter-${i + 1}`,
name,
nodes: ns .map (n => nodes .find (node => node .id == n)) .filter (Boolean)
}))
const data = {tableItems: [{id: 1, name: "1", startingPoint: true, pageNumber: 15, nodes: [100, 200]}, {id: 2, name: "2", startingPoint: true, pageNumber: 14, nodes: [300, 400]}], nodes: [{id: 100, tableItemId: 1, content: "test"}, {id: 200, tableItemId: 1, content: "test"}, {id: 300, tableItemId: 2, content: "test"}, {id: 400, tableItemId: 2, content: "test"}]}
console .log (transform (data))
.as-console-wrapper {max-height: 100% !important; top: 0}
This works similarly to the above except that it assigns the id at the same time as name and nodes.
I'm a founder of Ramda and remain a big fan. But it doesn't always add anything to vanilla modern JS.
You can use a curried function. Because the pipe will always pipe the result of the previous function call into the next function. You can use R.tap if you want to step over.
However, I guess you want to have the data object and the output of the previous function call both in your getNodes function. In that case you can use a curried function, where you pass the response of the previous function as last parameter.
const getNodes = R.curryN(2, function(data, tableItemList){
console.log(tableItemList) // result of previous function call
return R.pipe(
R.path(['nodes']),
R.map((node) => {
console.log('node:', node);
})
)(data)
})
And use it like:
R.pipe(
getChapters,
getNodes(data)
)(data)
I would split the solution into two steps:
Prepare the tableItems and nodes to the required end state using R.evolve - filter, sort, and then use R.toPairs the tableItems to get an array that includes the index and the object. Group the nodes by id so you can pick the relevant nodes by id in the combine step.
Combine both properties to create the end result by mapping the new tableItems, and using R.applySpec to create the properties.
const {pipe, evolve, filter, prop, sortBy, toPairs, groupBy, map, applySpec, path, flip, pick} = R
const transform = pipe(
evolve({ // prepare
tableItems: pipe(
filter(prop('startingPoint')),
sortBy(prop('pageNumber')),
toPairs
),
nodes: groupBy(prop('id'))
}),
({ tableItems, nodes }) => // combine
map(applySpec({
id: ([i]) => `chapter-${+i + 1}`,
name: path([1, 'name']),
nodes: pipe(path([1, 'nodes']), flip(pick)(nodes)),
}))(tableItems)
)
const data = {tableItems: [{id: 1, name: "1", startingPoint: true, pageNumber: 15, nodes: [100, 200]}, {id: 2, name: "2", startingPoint: true, pageNumber: 14, nodes: [300, 400]}], nodes: [{id: 100, tableItemId: 1, content: "test"}, {id: 200, tableItemId: 1, content: "test"}, {id: 300, tableItemId: 2, content: "test"}, {id: 400, tableItemId: 2, content: "test"}]}
console.log(transform(data))
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
I am stuck on a page where i am not able to display the charts on the page.
To make it simplify what I have done is, here is the code sandbox:
I see there an error in console about the data, I am not sure about it.
https://codesandbox.io/s/compassionate-snyder-bckoq
I want to display the chart like this (as an example), but I am not able to display on the code sandbox
Please help.
The format of series is not aligned with ApexCharts.
You need to transform the data to match with ApexChart format.
Please see the changes in the codesandbox.
https://codesandbox.io/s/small-dew-eztod?file=/src/components/HelloWorld.vue
options: {
// X axis labels
xaxis: {
type: 'date',
categories: ["2021-05-04", "2021-05-05", "2021-05-07"]
},
},
series: [
{
name: "total",
data: [2, 2, 1],
},
{
name: "pending",
data: [0, 1, 0],
},
{
name: "approved",
data: [2, 1, 1],
},
{
name: "rejected",
data: [0, 0, 0],
},
],
Transform data to fit ApexChart
const data = {
"2021-05-04": {
total: 2,
pending: 0,
approved: 2,
rejected: 0,
},
"2021-05-05": {
total: 2,
pending: 1,
approved: 1,
rejected: 0,
},
"2021-05-07": {
total: 1,
pending: 0,
approved: 1,
rejected: 0,
},
};
const xaxis = {
type: "date",
categories: Object.keys(data).map((key) => key), // ['2021-05-04', '2021-05-05', '2021-05-07']
};
let statusObj = [];
for (const dataValue of Object.values(data)) { // get the values from keys '2021-05-04', '2021-05-05' ...
// loop the values, e.g. 1st loop: { total: 2, pending: 0, approved: 2, rejected: 0, }
for (const [key, value] of Object.entries(dataValue)) {
// take 'total' as example, find if statusObj already has { name: 'total', data: [x] }, e.g. statusObj = { name: 'total', data: [1] }
const existingStatusIndex = Object.keys(statusObj).find(
(sKey) => statusObj[sKey].name === key
);
// if yes, return the index of it
if (existingStatusIndex) {
// add new data value to existing data object. e.g. { name: 'total', data: [1, 2] }
statusObj[existingStatusIndex].data.push(value);
continue;
}
// if no, create a new object and add it to statusObj
statusObj.push({
name: key,
data: [value],
});
}
}
Output:
xaxis {
type: 'date',
categories: [ '2021-05-04', '2021-05-05', '2021-05-07' ]
}
statusObj [
{ name: 'total', data: [ 2, 2, 1 ] },
{ name: 'pending', data: [ 0, 1, 0 ] },
{ name: 'approved', data: [ 2, 1, 1 ] },
{ name: 'rejected', data: [ 0, 0, 0 ] }
]
I have a table with parameters as shown below.
{
id: 1,
title: 'waccos',
description: 'Making an operating system in wacc',
est_duration: 420,
exp_req: 'any',
langs: [ 1 ],
owner: 1,
members: [ 1, 2 ]
},
I want to use SQL to add a new member into the member list, but I do not know how to. The table is called testprojects. I've tried using
(update testprojects
set members = members || $1
where title is $2;', [name, title])
but I think that is wrong. Could anyone help me please?
This is the table of members so far.
[
{ id: 1, name: 'A' },
{ id: 2, name: 'K' },
{ id: 3, name: 'S' },
{ id: 5, name: 'd' },
{ id: 6, name: 'J' },
{ id: 7, name: 'E' },
{ id: 8, name: 'a' }
]
I have this 'Products' array (contain 'Product' sub documents, each with its own unique Id):
Products: [
{ listPrice: '1.90', Product: {id: 'xxx1'} },
{ listPrice: '3.90', Product: {id: 'xxx2'} },
{ listPrice: '5.90', Product: {id: 'xxx3'} }
]
I want to get this result below using Lodash:
filterIds = ['xxx1', 'xxx2', 'xxx3'];
In my code, this is what I wrote:
filterIds = _.map(this.Products.Product, 'id');
But it just returns [ ].
You can do this using vanilla JS's Array.prototype.map method like so:
const arr = [{listPrice:'1.90',Product:{id:'xxx1'}},{listPrice:'3.90',Product:{id:'xxx2'}},{listPrice:'5.90',Product:{id:'xxx3'}}],
filtered = arr.map(obj => obj.Product.id);
console.log(filtered);
If you must use lodash:
const arr = [{listPrice:'1.90',Product:{id:'xxx1'}},{listPrice:'3.90',Product:{id:'xxx2'}},{listPrice:'5.90',Product:{id:'xxx3'}}],
res = _.map(arr, obj => obj.Product.id);
console.log(res);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
In Lodash
const _ = require('lodash');
const Products= [
{ listPrice: '1.90', Product: {id: 'xxx1'} },
{ listPrice: '3.90', Product: {id: 'xxx2'} },
{ listPrice: '5.90', Product: {id: 'xxx3'} }
]
console.log(_.map(_.map(Products, 'Product'), 'id'));
//[ 'xxx1', 'xxx2', 'xxx3' ]
I have two tables defined "posts" and "comments". I want to get all posts and a number of there total comments, split by the comment type. Currently I can get the count, but cannot separate by comment type
const Sequelize = require('sequelize');
const sequelize = new Sequelize('postgres://username#localhost:5432/test');
const posts = sequelize.define('posts', {
name: Sequelize.STRING,
})
const comments = sequelize.define('comments', {
title: Sequelize.STRING,
type: Sequelize.STRING
})
posts.hasMany(comments);
comments.belongsTo(posts);
const importData = async () => {
// Insert test data
await sequelize.sync({ force: true });
await posts.create({ id: 1, name: 'Hello World' })
await comments.create({ postId: 1, title: 'This is great', type: 'text' })
await comments.create({ postId: 1, title: 'Thanks', type: 'text' })
await comments.create({ postId: 1, title: 'Oh Yeah', type: 'image' })
await comments.create({ postId: 1, title: 'Oh Yeah', type: 'video' })
// Fetch data
const post = await posts.findAll({
where: { id: 1 },
attributes: ['id', 'name', [sequelize.fn('COUNT', 'comments.id'), 'commentCount']],
include: [{ model: comments, attributes: [] }],
group: ['posts.id']
})
console.log(JSON.stringify(post, null, 4))
}
importData();
Output is
[
{
"id": 1,
"name": "Hello World",
"commentCount": "4"
}
]
Desired Output
[
{
"id": 1,
"name": "Hello World",
"commentCount": { "text": 2, "image": 1, "video": 1 }
}
]
Can this be done through Sequelize, or even raw SQL?
Raw SQL something like:
SELECT P.ID, C.Comment_Count, C.Type
FROM POSTS P
LEFT JOIN (SELECT count(*) Comment_Count, PostID, type
FROM Comments
GROUP BY POSTID, type) C
on P.ID = C.PostID
change
PostID to the column name in comments that is the FK to posts
change ID to the PK in posts.