Why is there a "default" key in node json response? - node.js

As in the image, i am not sending any additional "Default" key but it is rendering
the whole json data as response again inside "default" key.
and i don't want it
what can be the reason for this ?
how can this be removed?"
here is the code snippet
import express from 'express'
import * as StateData from '../shared/indian_city_and_states.json';
import * as cuisines from '../shared/cuisines.json';
class MasterDataController {
public path: string="/master_data";
public router=express.Router();
constructor() {
this.intializeRoutes()
}
public intializeRoutes() {
this.router.get(`${this.path}/geo_data_list`,this.getRestaurants);
this.router.get(`${this.path}/cuisines_list`,this.getCuisines);
}
getRestaurants=async (
request: express.Request,
response: express.Response
) => {
return response.json(StateData)
}
getCuisines = (
request: express.Request,
response: express.Response
)=>{
return response.json(cuisines)
}
}
export default MasterDataController;
Here is what i am getting in response
{
"cuisines": [
"Bakery and Bread",
"Meat and Seafood",
"Pasta and Rice",
"Oils, Sauces, Salad Dressings, and Condiments",
"Cereals and Breakfast Foods",
"Soups and Canned Goods",
"Frozen Foods",
"Dairy, Cheese, and Eggs",
"Snacks and Crackers",
"Desserts",
"Beverages",
"Ice Cream",
"Fast foods",
"Coffee"
],
"default": {
"cuisines": [
"Bakery and Bread",
"Meat and Seafood",
"Pasta and Rice",
"Oils, Sauces, Salad Dressings, and Condiments",
"Cereals and Breakfast Foods",
"Soups and Canned Goods",
"Frozen Foods",
"Dairy, Cheese, and Eggs",
"Snacks and Crackers",
"Desserts",
"Beverages",
"Ice Cream",
"Fast foods",
"Coffee"
]
}
}

Related

Trying to display single user

I'm trying to create this logic a whole day and can't find anything helpful.. A small introduce of my app: While studying, I'm creating my local date app as practical job to improve more skills and logics. The problem is that I'm trying to get single user in main(home) page, when user login it should see already loaded single user from MongoDB where he can click like or dislike button. When user clicks one of them this user will push in user liked or dislike array and next user displays. I don't have like system yet, cause I can't get a single user. So later I wanna do filter method if user already liked or disliked other user, that one user didn't appear anymore and let users view his liked and disliked users.
So the main thing is that I have a get method where I'm getting all users and tried to create different routes to get only one of them, but can't imagine how to create correct logic of that.. 4-5 hours ago I tried to make for, map, forEach cycles but still can't understand the main logic here..
Here's my code, if it's not enough to understand just ask me for more code.
mainController(back-end):
getSingleUser: async (req, res) => {
const { secret } = req.params;
const findUser = await UserSchema.findOne({ secret });
if (findUser) {
return res.send({ error: false, message: 'User found', data: findUser });
}
return res.send({ error: true, message: 'User not found', data: null });
},
getAllUsers: async (req, res) => {
try {
const allUser = await UserSchema.find({});
res.status(200).json(allUser);
} catch (error) {
res.status(400).json({ message: error.message });
}
}
mainRouter(back-end):
const express = require('express')
const { login, register, getSingleUser, getAllUsers } = require("../controller/mainController")
const { loginValidate, registerValidate } = require("../middleware/authValidator")
const mainRouter = express.Router()
mainRouter.post('/register', registerValidate, register);
mainRouter.post('/login', loginValidate, login);
mainRouter.get('/api', getAllUsers)
mainRouter.get('/user/:secret', getSingleUser)
module.exports = mainRouter;
HomePage(front-end):
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import Toolbar from '../components/Toolbar';
import { get } from '../helper/helper';
import SingleUser from '../components/SingleUser';
export default function HomePage() {
const [allUsers, getAllUsers] = useState([])
const secret = window.localStorage.getItem('secret')
useEffect(() => {
async function fetchUsers() {
const resp = await get('api')
getAllUsers(resp)
}
fetchUsers()
}, [])
return (
<div className='home__page'>
<Toolbar />
<div className="home__users">
{allUsers && allUsers.filter(user => user.secret !== secret).map((users, i) => <SingleUser users={users} key={i} />)}
</div>
<footer className='footer'>
<p>All rights reserved by Cartoon Match organization. To read more about our policy <Link to='/policy'>click here</Link>. </p>
</footer>
</div>
)
}
This is result of HomePage users fetch:
[
{
"_id": "638e31a2579ba2a13b454943",
"image": [
"https://picsum.photos/id/377/4884/3256",
"https://picsum.photos/id/378/5000/3333"
],
"username": "testas",
"firstName": "testas",
"lastName": "testas",
"email": "test#gmail.com",
"gender": "male",
"city": "asdadas",
"country": "aasdasd",
"birth": "2020-02-20",
"phone": "65asd15a6sd",
"password": "$2b$04$zpqQVU7cFUfdA9DCfKmFYOOdY93OVPXoQq08kM87ehwwxD25/pl6q",
"likes": [],
"liked": [],
"secret": "Ey2_-dVlpg",
"__v": 0
},
{
"_id": "639130a43c2e51dc08531019",
"image": [
"https://www.1zoom.me/big2/98/183590-20043.jpg",
"https://pngimg.com/uploads/shrek/shrek_PNG22.png"
],
"username": "SirShrek",
"firstName": "Sir",
"lastName": "Shrek",
"email": "callmeshrek#swamp.com",
"gender": "male",
"city": "Swamp",
"country": "Fairy-Tale Land Of Duloc",
"birth": "1999-02-27",
"phone": "830-476-5664",
"password": "$2b$04$u1jacGrx6yWOMxfkllMxWO.5in4rQDFIbbCMMixzHqV9rObtq1tKG",
"likes": [],
"liked": [],
"secret": "FP8Rd4izgQ",
"__v": 0
},
{
"_id": "6391c8df7f83052432e2d939",
"image": [
"https://static.wikia.nocookie.net/vsbattles/images/e/e8/Dexter_Rendered.png/revision/latest?cb=20180919045250",
"https://i.ebayimg.com/images/g/VesAAOSwrohehKhn/s-l1600.jpg"
],
"username": "Dexter",
"firstName": "Dexter",
"lastName": "Michael Louis McPherson lll",
"email": "dexter#science.com",
"gender": "male",
"city": "Genius Grove",
"country": "Peter Lorre",
"birth": "2014-12-31",
"phone": "555-0100",
"password": "$2b$04$BMUidKOaRBtWDNKH.NduB.gkgzUhPNuXVk10ip7lPo/N/1k/8sxvW",
"likes": [],
"liked": [],
"dislike":[],
"secret": "9k6ilC2ZZg",
"__v": 0
}]
This is SingleUser component:
import React, { useEffect, useState } from "react";
import MainContext from '../context/MainContext'
import { get, put } from '../helper/helper'
export default function SingleUser({ users }) {
return (
<div className='single__user'>
<img src={users.image[0]} alt="" />
<h3>{users.firstName} {users.lastName}</h3>
<h4>{users.gender}</h4>
<button>Dislike</button>
<button onClick={postLikes}>Like</button>
</div>
);
}

How to perform a filter on a json result using python

I have the json response below returned from an api call.
{
"custAnalysis": [
{
"custPermId": "1234",
"custType": "Business",
"taxId": "8888",
"custAddr": {
"fullName": "Testing LIMITED",
"addr1": "6734 APAPA RD"
}
},
{
"custPermId": "5678",
"custType": "Business",
"taxId": "9999",
"custAddr": {
"fullName": "SUPERMAN LLC",
"addr1": "6734 APAPA RD"
}
},
{
"custPermId": "9234",
"custType": "Business",
"taxId": "8888",
"custAddr": {
"fullName": "DONALD LLC",
"addr1": "6734 APAPA RD"
}
}
]
}
I want to be able to search the json result above for a taxId of 8888. If taxId = 8888
return another json in the format below with the result
{
"custQueryResult": {
"custPermId": 1234,
"custPermId": 9234
}
}
I am very new to python. How can I achieve this in Python?
search_texId=8888
search_result={"custQueryResult":[]}
for obj in response_dict["custAnalysis"]:
if int(obj["taxId"])==search_texId:
search_result["custQueryResult"].append({"custPermId": int(obj["custPermId"])})
print(search_result)
Dictionary couldn't assign the same name keys. SocustPermId will be listed under custQueryResult key

Set Parameters Output Context from Looping on Dialogflow

i make some loop for calling data from firebase, how to set document id as parameters for my output context when i selected the data from document?
this my code for function daftaKota
function daftarKota(agent){
const query = db.collection('kota');
return query.get().then(s =>{
if (s.empty){
agent.add('belum ada kota yang didaftarkan oleh Pemilik');
agent.add('untuk mengakses menu lainnya silahkan ketikan "menu"');
agent.context.set('menu',2);
} else {
agent.add('berikut daftar kota');
s.forEach(doc =>{
agent.add(new Suggestion(doc.data().nama_kota));
agent.context.set('lihat-toko',5,{'id_kota' : doc.id,'nama_kota' : doc.data().nama_kota});
});
}
});
this my code for function daftarToko
function daftarToko (agent){
const context = agent.context.get('lihat-toko');
const idKota = context.parameters.id_kota;
const nKota = agent.parameters.kota;
const query = db.collection('toko').where('id_kota','==',idKota);
return query.get().then(s =>{
if (s.empty){
agent.add('Belum ada Toko yang didaftarkan di kota ini');
agent.add('untuk mengakses kota lainnya silahkan ketikan "kembali"');
agent.context.set('order',2);
}else{
agent.add('berikut daftar toko di kota '+nKota);
s.forEach(doc => {
agent.add(new Card({title : doc.data().nama_toko, imageUrl : doc.data().gambar_toko}));
agent.add(new Suggestion(doc.data().nama_toko));
agent.context.set('lihat-kue',5,{'id_toko' : doc.id});
});
}
});
and this the Intent Map
intentMap.set('Daftar Kota',daftarKota);
intentMap.set('Daftar Toko',daftarToko);
this my intent "Daftar Kota"
this intent show the city from database using suggestion
when i selected the other suggestion city like Yogyakarta, Jakarta, or Bandung, the parameters still set on Banjarmasin.
this my API response after i select Yogyakarta
{
"responseId": "9e1daa4d-31f8-4a62-a939-813be357a634-19db3199",
"queryResult": {
"queryText": "Yogyakarta",
"parameters": {
"kota": "Yogyakarta"
},
"allRequiredParamsPresent": true,
"fulfillmentMessages": [
{
"text": {
"text": [
"Belum ada Toko yang didaftarkan di kota ini"
]
}
},
{
"text": {
"text": [
"untuk mengakses kota lainnya silahkan ketikan \"kembali\""
]
}
}
],
"outputContexts": [
{
"name": "projects/jastip-21e34/agent/sessions/771d2ffc-b490-51f3-7da7-78b91faa8ad3/contexts/order",
"lifespanCount": 2
},
{
"name": "projects/jastip-21e34/agent/sessions/771d2ffc-b490-51f3-7da7-78b91faa8ad3/contexts/lihat-toko",
"lifespanCount": 4,
"parameters": {
"kota": "Yogyakarta",
"nama_kota": "Banjarmasin",
"id_kota": "qCjS54XPf1lAtECUFTTw",
"kota.original": "Yogyakarta"
}
}
],
"intent": {
"name": "projects/jastip-21e34/agent/intents/f14ab0fa-b506-419d-a360-a8eb7cd84b93",
"displayName": "Daftar Toko"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 236
},
"languageCode": "id"
},
"webhookStatus": {
"message": "Webhook execution successful"
}
}
see at paramers :
i selected "kota : Yogyakarta",
but the id_kota is the document id of nama_kota "Banjarmasin", not the id of "Yogyakarta"
You're not showing the query that you're using, or where you're storing the parameters you get, but in your loop you're not actually checking to see if nama_kota matches the kota that is sent through the parameters. So it is changing the context every time it goes through the loop, and ends up with the new parameters from the last time through.
One solution would be to check if they match and, when they do, set the context.
s.forEach(doc =>{
agent.add(new Suggestion(doc.data().nama_kota));
if( parameters.kota === doc.data().nama_kota ){
agent.context.set('lihat-toko',5,{'id_kota' : doc.id,'nama_kota' : doc.data().nama_kota});
}
});

find by category in array object not working in Angular frontend

I'm trying to build a blog application using Angular on frontend with node, express in the backend and mongodb as database. Now I'm trying to make a component called blog-categories where there should be a method to iterate the whole database and search by the key category and return the values in the component such that all the category values are now shown in the component and when someone will click the values all blogs having such categories will get displayed. In case if you want to have a better look at the project you can check out my git repository https://github.com/tridibc2/blog-admin-mean . But it seems that the route is not able to catch the category. In the header it is going null. localhost:4000/api/v1/blogs/view/by/category/null The typical database looks somewhat like this:
{
"error": false,
"message": "All Blogs found Successfully",
"status": 200,
"data": [
{
"title": "Blog Title 2 Custom edited",
"description": "Blog description 2 Custom Edited",
"bodyHtml": "<h3>Heading of the body CUSTOM</h3><p>This is the first blog data getting uploaded n blog project</p>\nedited",
"views": 9,
"isPublished": true,
"category": "Comedy",
"author": "Decardo",
"tags": [
"english movies, action movies, comedy"
],
"blogId": "nbfO8hJp",
"created": "2020-01-04T23:33:38.000Z",
"lastModified": "2020-01-04T23:33:38.000Z"
},
{
"title": "Blog Title 2",
"description": "Blog description 2",
"bodyHtml": "",
"views": 1,
"isPublished": true,
"category": "tech",
"author": "Xtremator",
"tags": [
"english movies",
" action movies",
" comedy"
],
"blogId": "ZW8OR7vc",
"created": "2020-01-04T23:34:08.000Z",
"lastModified": "2020-01-04T23:34:08.000Z"
}
]
}
blog-category.component.ts
import { Component, OnInit } from '#angular/core';
import { BlogpostService } from '../blogpost.service';
import { Router, ActivatedRoute} from '#angular/router';
#Component({
selector: 'app-blog-category',
templateUrl: './blog-category.component.html',
styleUrls: ['./blog-category.component.css']
})
export class BlogCategoryComponent implements OnInit {
public categories;
constructor(private blogpostService: BlogpostService, private route: ActivatedRoute,
private router: Router) { }
ngOnInit() {
let myBlogcatrgory = this.route.snapshot.paramMap.get('category');
this.blogpostService.viewByCategory(myBlogcatrgory).subscribe(
data =>{
console.log(data);
this.categories = data["category"];
},
error =>{
console.log("some error occured");
console.log(error.errorMessage);
}
);
}
}
blog-category.component.html
<h3>Categories</h3>
<ul>
<li *ngFor="let category of categories">
{{category.name}}
</li>
</ul>
</div>

How can I get participant/organization inside convector controllers?

I want to get participant model inside controller, but I only have identity/fingerprint....
The question is how to get the participant model?
the answer is use the identity/fingerprint with a rich couchdb query.
inside controller use this.sender to get fingerprint ex B5:38:A3:84:02:D1:EE:2B:CD:25:27:66:C0:F6:9E:4F:91:16:21:EE
next, first create the worldstate query, and test it in fauxton
query
{
"selector": {
"type": "io.worldsibu.examples.participant",
"identities": {
"$elemMatch": {
"fingerprint": "B5:38:A3:84:02:D1:EE:2B:CD:25:27:66:C0:F6:9E:4F:91:16:21:EE",
"status": true
}
}
}
}
done with query
now create a utils.ts to be shared in controllers like
packages/person-cc/src/utils.ts
import { appConstants as c } from '#convector-rest-sample/common';
import * as bcrypt from 'bcrypt';
import { Participant } from 'participant-cc';
const bcryptSaltRounds: number = 10;
export const hashPassword = (password: string): string => {
return bcrypt.hashSync(password, bcryptSaltRounds);
};
/**
* get Participant by Identity/Fingerprint
*/
export const getParticipantByIdentity = async (fingerprint: string): Promise<Participant> => {
const participant: Participant | Participant[] = await Participant.query(Participant, {
selector: {
type: c.CONVECTOR_MODEL_PATH_PARTICIPANT,
identities: {
$elemMatch: {
fingerprint,
status: true
}
}
}
});
if (!!participant && !participant[0].id) {
throw new Error('Cant find a participant with that fingerprint');
}
return participant[0];
}
now use it in one controller
...
import { getParticipantByIdentity, hashPassword } from './utils';
#Controller('person')
export class PersonController extends ConvectorController<ChaincodeTx> {
#Invokable()
public async create(
#Param(Person)
person: Person
) {
// get host participant from fingerprint
const participant: Participant = await getParticipantByIdentity(this.sender);
if (!!participant && !participant.id) {
throw new Error('There is no participant with that identity');
}
...
done, now deploy chaincode and test with
npx hurl invoke $CC person_create "{\"id\":\"1-100-100\",\"firstname\":\"Pete\",\"lastname\":\"Doe\",\"username\":\"peter\",\"password\":\"12345678\",\"email\":\"pete.doe#example.com\"}" -u admin
check couchdb
{
"_id": "1-100-100",
"_rev": "1-2b08d163d01dcfa5b9e9dc31bcc3b50c",
"email": "pete.doe#example.com",
"firstname": "Pete",
"id": "1-100-103",
"lastname": "Doe",
"participant": {
"id": "gov",
"identities": [
{
"fingerprint": "B5:38:A3:84:02:D1:EE:2B:CD:25:27:66:C0:F6:9E:4F:91:16:21:EE",
"status": true
}
],
"msp": "org1MSP",
"name": "Big Government",
"type": "io.worldsibu.examples.participant"
},
"password": "$2b$10$IYsgUSb/RA6zr4tT3u10HugCrxJH2loLsVUKjTkTiAAj3yewnR2SO",
"roles": [
"USER"
],
"type": "io.worldsibu.examples.person",
"username": "peter",
"~version": "\u0000CgMBDgA="
}
done

Resources