i believe brackets are throwing off my data fetching from JSON object - javascript

Hi everyone i am looking for some help fetching data from a JSON object within a next.js api route. I am able to print the entire object with (body.req), however I am not sure how to do access the 'name' value since there is no brackets around the JSON object.
my api route looks something like this
api/site.js
import { createSite, deleteSite, getSite, updateSite } from "#/lib/api";
import { unstable_getServerSession } from "next-auth/next";
import { authOptions } from "./auth/[...nextauth]";
import { HttpMethod } from "#/types";
import * as fs from 'fs';
export default async function site(req, res) {
...
case HttpMethod.DELETE:
// *****************************************************
const obj = JSON.parse(req.body);
// *****************************************************
const finalJSON = JSON.stringify(obj);
console.log(finalJSON)
return deleteSite(req, res);
...
default:
res.setHeader("Allow", [
HttpMethod.GET,
HttpMethod.POST,
HttpMethod.DELETE,
HttpMethod.PUT,
]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
I have tried adding brackets around the createSite function
export async function createSite(
req,
res
) {
const { name, username, description, userId } = req.body;
// const sub = subdomain.replace(/[^a-zA-Z0-9/-]+/g, "");
try {
// *****************************************************
const response = await prisma.site.create([{
data: {
name: name,
username: username,
description: description,
user: {
connect: {
id: userId,
},
},
},
}]);
// *****************************************************
res.status(201).json({
siteId: response.id,
});
} catch (error) {
console.error(error);
res.status(500).end(error);
}
}
which is also throwing an error.
I am able to print the entire body of the request to the console which looks something like this
{
"id": "clapi474y4547coe62775z30k",
"name": "0100",
"createdAt": "2022-11-20T15:16:12.178Z",
"updatedAt": "2022-11-20T15:16:12.179Z",
"userId": "clab8z2544207e17ve73c3rqc"
}
I am trying to access the just name inside this delete api and I have tried changing
const obj = JSON.parse(req.body);
to
const obj = JSON.parse(req.body.name);
my console then returns undefined.
what is the correct way to access this data? (the name's value type might be either just numbers or letters or a combination of both.)
If anyone can help me out with this it would be greatly appreciated.
Thanks y'all

Related

React Native: Convert the value stored in AsyncStorage into an object

I am making a simple CRUD app using React Native with MongoDB, NodeJS and Express. When the user registers, the _id is saved inside AsyncStorage to check if the user is already authenticated or not every time he/she opens the app.
const response = await axios.post('API_LINK', {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
})
const data = await response.data
console.log(data)
await AsyncStorage.setItem('userId', data.user._id)
console.log(data) returns
Object {
"user": Object {
"__v": 0,
"_id": "62e42244b7bc9e7f9de5131b",
"email": "testing5#gmail.com",
"name": "Test 5",
"password": "$2a$10$SE7Eq46mBXGw7FYBtOtqqO49wvIMYDl0LfHknrrp.rWdrYNr6Dk8.",
"projects": Array [],
},
}
The projects [] contains all the projects created by that particular user. So, in the Project Model and Controller, the userId is also passed, so that the specific project is stored in the projects array of that specific user whose userId is passed.
ProjectModel
const projectSchema = new Schema({
title: {
~~~~~~~~~~~~~~~~~~~~~~~~~~~
},
description: {
~~~~~~~~~~~~~~~~~~~~~~~~~~~
},
user: {
type: mongoose.Types.ObjectId,
ref: 'User',
required: true
}
})
Project Controller
export const createProject = async (req, res, next) => {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
let userExists
try {
userExists = await User.find(user)
} catch (err) {
return console.log(err)
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const project = new Project({
title,
description,
user
})
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
CreateProject
const userId = await AsyncStorage.getItem('userId')
const response = await axios.post('http://IP_ADDRESS:8000/api/project/create', {
title: title.trim(),
description: description.trim(),
image: image.trim(),
user: userId
})
But on clicking Create button, this error is shown
ObjectParameterError: Parameter "filter" to find() must be an object, got 62e42244b7bc9e7f9de5131b, linking to the createProject inside Project Controller.
Then, I saw that _id stored as userId is string, so I tried to convert it to object using JSON.parse().
const userId = await AsyncStorage.getItem('userId')
const userId2 = JSON.parse(userId)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
user: userId2
But, now I get this error JSON Parse error: Unable to parse JSON string.
So, how to convert the userId stored in AsyncStorage into object? And, if there are any other better methods to perform this task, please suggest.

Google nodejs client library return empty account list

What I am trying to do is using google api nodeJs client library to list accounts at my google tag manger using service key json file every thing works but I got an empty accounts, however I have one account, I tries several things but can't figure out what's wrong
This my code:
import { google, Auth } from "googleapis";
import * as path from "path";
const SCOPES = [
"https://www.googleapis.com/auth/tagmanager.edit.containers",
"https://www.googleapis.com/auth/tagmanager.readonly",
"https://www.googleapis.com/auth/tagmanager.manage.accounts",
];
const main = async () => {
try {
const tagManager = await initTagManagerObject();
const accounts = await tagManager.accounts.list({
pageToken: "dummy",
});
console.log("accounts", accounts.data); // prints {}
} catch (error) {
console.log("error", error);
}
};
const initTagManagerObject = async () => {
const serviceAuth = new Auth.GoogleAuth({
keyFile: path.join(__dirname, "../tag-manager-360107-9b3448dfc173.json"),
// Scopes can be specified either as an array or as a single, space-delimited string.
scopes: SCOPES.join(" "),
});
console.log(
"ff",
path.join(__dirname, "../tag-manager-360107-9b3448dfc173.json")
);
const client = await serviceAuth.getClient();
const tagManager = await google.tagmanager({
version: "v2",
auth: client,
});
return tagManager;
};
main();
This is service key json file format
{
"type": string,
"project_id": string,
"private_key_id": string,
"private_key": string,
"client_email": string,
"client_id": string,
"auth_uri": string,
"token_uri": string,
"auth_provider_x509_cert_url": string,
"client_x509_cert_url": string,
}
here's screen shot of my service key
Please help me in this and thanks in advance

res.send() not sending back complete data set

hoping you all can help me solve this mystery. I’ve created an endpoint for my API:
apiRouter.get("/username", async (req, res) => {
const { username } = req.body;
try {
const user = await getUserByUsername(username);
res.send({ message: "This is your user", user });
console.log("this is user", user);
} catch (error) {
throw error;
}
});
It’s a GET route that should send back the a message and a user object in this fashion when the user interacts with this url path:
http://localhost:3000/api/users/username
When I access the endpoint via, Postman, I get back both the message and the user object. Something that looks like this:
{
"message": "This is your user",
"user": {
"customer_id": 5,
"first_name": "Jessica",
"last_name": "Blue",
"email": "baker#space.com",
"username": "jess1",
"password": "1234",
"address_1": "123 pretty lane",
"address_2": "Apt 31",
"city": "Riverside",
"state": "California"
}
}
However, when I access the route, via my frontend, the message comes back but not the user. I’m using the following method to make the call to the server:
export async function getUserByUsername(username) {
try {
const { data } = await axios.get("/api/users/username", {
username,
});
console.log(data);
return data;
} catch (error) {
throw error;
}
}
I'm really not sure why the user isn’t being sent back with the response. The route works, I’m just not getting back my expected response. I’ve spent a couple hours trying to find a fix with no luck. Any help would be greatly appreciated.enter image description here
Currently you can't send a body with get requests in most browsers. so you've two options:
change your backend method to POST:
apiRouter.post("/username", async (req, res) => {
const { username } = req.body;
.
.
.
}
and use axios like this:
const { data } = await axios.post("/api/users/username", {
username,
});
or if you want to stick with the get method accept the username as a query or a param:
apiRouter.get("/username/:username", async (req, res) => {
const { username } = req.params;
.
.
.
}
and use axios like this:
const { data } = await axios.get(`/api/users/username/${username}`);
or
apiRouter.get("/username", async (req, res) => {
const { username } = req.query;
.
.
.
}
and use axios like this:
const { data } = await axios.get(`/api/users/username`, { params: { username } });
You are using a GET request with body. Although it's possible, but not advisable, to do so when you create your own request through Postman, axios probably ignores the body param when using a GET request and doesn't include it in the request.
So my suggestion would be to place the username param in the request params (req.params) or request query (req.query) and try to get it from there.
You can find more details about req.params: here, and about req.query: here.
I think it's might be because of the async await approach you're using in the endPoint it self, can you try running this line in your terminal:
npm install express-async-errors --save
after that go to index.js (your backend route file) and add this line over here:
import 'express-async-errors';
and try again, Hopefully, this will solve your issue

Prisma throws an error "TypeError: cannot read property findmany of undefined"

I wanted to make a chat app to practice working with graphql and node, for database I used prisma. I was doing everything like in this tutorial.
https://www.howtographql.com/graphql-js/0-introduction/
I just changed variable names.
so I have this code
const { PrismaClient } = require('#prisma/client')
const prisma = new PrismaClient()
const resolvers = {
Query: {
history: async (parent, args, context) => {
return context.prisma.Messages.findMany()
},
},
Mutation: {
post: (parent, args, context) => {
const newMessage = context.prisma.Messages.create({
data: {
username: args.username,
message: args.message,
},
})
return newMessage
},
},
}
const server = new GraphQLServer({
typeDefs: './src/schema.graphql',
resolvers,
context: {
prisma,
}
})
server.start(() => console.log(`Server is running on http://localhost:4000`))
as my index.js
this is my schema.prisma
provider = "sqlite"
url = "file:./dev.db"
}
generator client {
provider = "prisma-client-js"
}
model Message {
id Int #id #default(autoincrement())
sendedAt DateTime #default(now())
message String
username String
}
script.js
const { PrismaClient } = require("#prisma/client")
const prisma = new PrismaClient()
async function main() {
const newMessage = await prisma.Messages.create({
data: {
message: 'Fullstack tutorial for GraphQL',
username: 'www.howtographql.com',
},
})
const allMessages = await prisma.Messages.findMany()
console.log(allMessages)
}
main()
.catch(e => {
throw e
})
// 5
.finally(async () => {
await prisma.disconnect()
})
and schema.graphql
type Query {
history: [Message!]!
}
type Mutation {
post(username: String!, message: String!): Message!
}
type Message {
id: ID!
message: String!
username: String!
}
and that is what i got in my playground
"data": null,
"errors": [
{
"message": "Cannot read property 'findMany' of undefined",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"history"
]
}
]
}
please help
I managed to fix that. Actually, all I needed was to use the same name but lowercased as in schema.prisma
It should be noted it is not actually lowercase but camel case.
Example:
Model name: Message -> Prisma client name: message
Model name: MessagePerUser -> Prisma client name: messagePerUser
Would like to add on to the answer
Basically when calling await prisma.User.create, prisma allows the User model to be in caps, but when calling other models such as prisma.messages.create the m has to be in lowercase. Essentially,for all prisma calls, the models should be in lowercase. Hopefully this answers your question, prisma does not flag this error out
use Table name as camelCase in prisma Client to make Queries
Example:
Table Name is: StudentData
then use camelCase according to table name
prisma.studentData.findMany();

How to convert from JSON to XML

I need to convert some JSON to XML with this library, I need to do that in order to send some data to the Database in a post request I am working on.
This is what req.body returns
{ DealerName: 'amrcl',
CardId: '123',
Nickname: 'mkm123',
Picture: 'http://lorempixel.com/150/150/',
Active: '1',
LegalId: '1',
TypeId: '1'
}
is dynamic data. Let me show you the code
export default function (req, res) {
try {
const connection = new sql.Connection(spConfig, function spConnection (errSpConnection) {
const request = connection.request();
if (errSpConnection) {
res.status(401);
}
request.input('Dealer_Param', sql.VarChar(1000), req.body);
request.input('param_IS_DEBUG', sql.Bit, null);
request.output('output_IS_SUCCESSFUL', sql.Bit);
request.output('output_STATUS', sql.VarChar(500));
request.execute('[mydbo].[StoredProcedure]', function spExecution (errSpExecution, dataset) {
connection.close();
if (errSpExecution) {
res.status(401);
} else {
if (request.parameters.output_IS_SUCCESSFUL.value) {
res.status(200).json({
success : 'New dealer successfully inserted.',
});
}
}
});
});
}
}
that is for Stored Procedure method which is with the mssql module.
As you see the code above, there is a failure error, because in request.input('Dealer_Param', sql.VarChar(1000), req.body); I am sending the JSON I paste at the beginning of the question. But if instead of req.body I put this XML with Dummy data '<Dealers><Detail DealerName = "TESTING123" CardId = "1222" NickName = "tester123" Active = "1" LegalId = "16545" TypeId = "1"></Detail></Dealers>' then everything works fine because the DB need to receive an XML.
So, what are your recommendations, what should I do to put the JSON data as a XML ?
I would just load the json2xml library...
install $ npm install json2xml
import the module in your code: var json2xml = require("json2xml");
and then convert the json to xml like so:
var key,
attrs=[];
for (key in req.body) {
if (req.body.hasOwnProperty(key)) {
var obj = {};
obj.key = req.body.key;
attrs.push(obj);
}
}
var dealerXml = json2xml({dealer:req.body, attr:attrs}, { attributes_key:'attr'});
request.input('Dealer_Param', sql.VarChar(1000), dealerXml);

Categories