Contentful Unknown Content Type - contentful

We are trying to query for content in Contentful CMS and we are receiving the following error:
errors: [ { name: 'unknownContentType', value: 'DOESNOTEXIST' } ]
This query had been previously work and the Content Type does exist in the backend.
Anyone experienced this problem before?
This is out query:
const result = await client
.getEntries({
content_type: "page",
"fields.path": context.params.slug,
})
.then((response) => {
return response.items
})

I am trying to locate my solution in the docs but, JSON stringifying the query worked for me:
const query = JSON.stringify({
content_type: "page",
"fields.path": context.params.slug,
})
const result = await client
.getEntries(query)
.then((response) => {
return response.items
})

Related

product image not showing up when using stripe checkout in my nodejs application

Below is the code for my checkout route.
Everything works except for one line: images: [`${process.env.SERVER_URL}/public${item.itemData.images[0]}`]
I tried to console log this path and got the correct one: "http://localhost:5000/public/image/test_image_2.webp" Therefore, I am confused as to why this doesnt work. I am pretty sure the images feild takes an array of image paths for each product, and that is what I have given it, but still I am seeing the little cant find image symbole instead of my product image. What do I do?
const router = require("express").Router();
const Product = require("../models/product-schema");
const { default: Stripe } = require("stripe");
const { getUser, authUser, authAdmin, authAdmin404 } = require("../middleware/authentication");
const stripe = require("stripe")(process.env.STRIPE_PRIVATE_KEY);
router.post("/create-checkout-session", authUser, async (req, res) => {
try {
const unresolved = req.body.items.map(async (item, index, arr) => {
const storeItem = await Product.findById(item.id);
return arr[index] = { itemData: storeItem, quantity: item.quantity };
});
const items = await Promise.all(unresolved);
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
mode: "payment",
line_items: items.map((item) => {
return {
price_data: {
currency: 'eur',
product_data: {
name: item.itemData.product_name,
images: [`${process.env.SERVER_URL}/public${item.itemData.images[0]}`]
},
unit_amount: item.itemData.price_in_cents,
},
quantity: item.quantity,
}
}),
success_url: `${process.env.SERVER_URL}/`,
cancel_url: req.body.url,
});
res.json({ url: session.url });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
module.exports = router;
Stripe will download each image at the URL(s) you provide and cache them locally. When you give a URL that is based on localhost though it has no way to access the data so it just can't cache it and display it later.
You need to make sure that the URL you provide is publicly accessible for them to cache it. It's also possible for your server to be mis-configured (bad TLS certificate for example) causing the attempt to fetch the image to fail and so Stripe will just not render it in that case.

Validation error of type UnknownType: Unknown type CreateUserInput

Using AppSync Query Playground running this query.
mutation UserMutation ($input: CreateUserInput!) {
createUser
(input: $input)
{
uniqueID
recordType
userName
userEmail
userEmailVerified
userCreated
userLastModified
userEnabled
userStatus
userValidFrom
userValidTo
}
}
Query Variables are
{
"input":
{
"uniqueID": "UUID-formatted",
"recordType": "USER",
"userName": "username",
"userEmail": "mailadres",
"userEmailVerified": true,
"userCreated": "2020-12-04T22:32:37.000Z",
"userLastModified": "2020-12-04T22:34:15.000Z",
"userEnabled": true,
"userStatus": "CONFIRMED",
"userValidFrom": "2021-03-12T11:03:37.283Z",
"userValidTo": "9999-12-31T23:59:59.999Z"
}
}
Creates a record in the DynamoDB table as expected.
Which suggest to me that the model and the resolvers are well defined in AppSync.
Running the exact same code in a NodeJS Express environment creates the above error.
API-key and GraphQL endpoint are correct. Exactly the same method for other entity used and works.
This is the NodeJS code
exports.userCreate = (cognitosub, userName, cognitoemail, cognitoemail_verified, cognitoUserCreateDate, cognitoUserLastModifiedDate, cognitoEnabled, cognitoUserStatus, userValidFrom, userValidTo) => {
const mutateQuery = gql(`
mutation UserMutation ($input: CreateUserInput!) {
createUser
(input: $input)
{
uniqueID
recordType
userName
userEmail
userEmailVerified
userCreated
userLastModified
userEnabled
userStatus
userValidFrom
userValidTo
}
}
`);
const mutateVariables = JSON.parse(`{
"uniqueID" : "${cognitosub}",
"recordType" : "USER",
"userName" : "${userName}",
"userEmail" : "${cognitoemail}",
"userEmailVerified" : ${cognitoemail_verified},
"userCreated" : "${cognitoUserCreateDate}",
"userLastModified" : "${cognitoUserLastModifiedDate}",
"userEnabled" : ${cognitoEnabled},
"userStatus" : "${cognitoUserStatus}",
"userValidFrom" : "${utils.dateConvertToISOString(userValidFrom)}",
"userValidTo" : "${utils.dateConvertToISOString(userValidTo)}"
}`)
return new Promise ((resolve, reject) => {
console.debug(`${Date(Date.now())} - utilities.userCreate.mutateVariables`,mutateVariables)
graphqlClient.mutate({
mutation: mutateQuery,
fetchPolicy: 'no-cache', // Mutate suporteert alleen 'no-cache'
variables: {input: mutateVariables}
})
.then((success) => {
// console.debug(`${Date(Date.now())} - utilities.userCreate.then`,success)
if (success === null) {reject('userIsNull')}
else {
resolve(success.data.createUser.uniqueID)}
})
.catch((err) => {
console.debug(`${Date(Date.now())} - utilities.userCreate.catch\n`,err)
reject(err)
})
})
Exact same code is used for a less complicated object with an UUID, Identification, validFrom en ValidTo date. It works like a charm.
I looked at every error and spelling mistake. The code keeps throwing this two errors.
graphQLErrors: [
{
path: null,
locations: [ { line: 1, column: 31, sourceName: null } ],
message: 'Validation error of type UnknownType: Unknown type CreateUserInput'
},
{
path: null,
locations: [ { line: 2, column: 3, sourceName: null } ],
message: "Validation error of type FieldUndefined: Field 'createUser' in type 'Mutation' is undefined # 'createUser'"
}
]
Which are dump of the error-object.
Appolo-client is used top access the DynamoDB. The records created in the AppSync GraphQL playground are perfectly viewable in the DB.
I am out of clues here. Can anyone help?
Today I really looked into this problem and decided not to use the AppSync client from AWS anymore (which created some depency build problems with every npm update by the way...)
I choose to go for the Apollo client latest version which doesn't give any npm update issues and is a up-to-date version of the client that AWS uses in the background if I am well informed (read can read fora in a good way ;-))
I had some issues with the authentication on AppSync but managed to get over this.
This code totally fixes ALL previous error (for me)
const gql = require("graphql-tag");
const ApolloClient = require("#apollo/client").ApolloClient
const ApolloLink = require("#apollo/client").ApolloLink
const InMemoryCache = require("#apollo/client").InMemoryCache;
const createHttpLink = require("#apollo/client").createHttpLink;
const {createAuthLink} = require("aws-appsync-auth-link")
require('cross-fetch/polyfill');
const clientGraphQL = new ApolloClient({
link: ApolloLink.from([
createAuthLink({
url: aws_secrets.AWS_DEV_APPSYNC_ENDPOINT,
region:aws_secrets.REGION,
auth:
{
type: "API_KEY",
apiKey: aws_secrets.AWS_DEV_APPSYNC_API_KEY,
}
}),
createHttpLink({
uri: aws_secrets.AWS_DEV_APPSYNC_ENDPOINT
}),
]),
cache: new InMemoryCache(),
});
Safe code by hiding all the secrets in a special file.
createAuthLink is the only thing I need from AWSAppSync (IMHO).
I didn't manage to get a proper connection with the CreateAuthLink from the Apollo Client.
Hope this helps some of you...

how can we use data received through axios put request on client side in mern stack?

I have sent category Id to the Nodejs through this code
const catHandler = async (catId) => {
const data = Axios.put('/api/products/categories/filter', {catId: catId},
{
"headers": { "content-type": "application/json", },
}
).then( categoriesProducts => {
console.log(categoriesProducts.data.products)
})
}
and this is my route for this
router.put('/categories/filter', async (req, res) => {
try {
const findCategory = await Category.find({ _id: req.body.catId });
if (findCategory) {
const productsByCategory = await Product.find(
{ category: req.body.catId }
).then(products => {
res.status(200).json({ products });
})
}
} catch (error) {
console.log('categories filter error', error)
}
})
The products of specific category are being shown in the console.log(categoriesProducts.data.products) on the react front end side like below
0: {_id: "5f7c88756746363148792982", name: "Simple Pizza", price: 5.6, image: "1601996916374.jpg", countInStock: 434, …}
1: {_id: "5f7c88976746363148792983", name: "Smoked Pizza", price: 7.8, image: "1601996951114.jpg", countInStock: 88, …}
2: {_id: "5f7c88c56746363148792984", name: "Large Cheezy Pizza", price: 9.4, image: "1601996997474.jpg", countInStock: 434, …}
But I want to display these products on the front end side. I have tried to use axios.get method but with get method how can I can send category Id to backend. So if any one has any idea how to do that Plz guide me.
you can use the query params with get method in node js
you can get query params by req.query in nodeJs
example
passing category id from front end -
api/products/categories/filter?cid=1
getting query param in the backend
const catId = req.query.cid
You can use below code to pass parameter to API get method.
fetch("/api/products/categories/filter?catId" + catId)
.then((res) => res.json())
.then((json) => {
this.setState({
Items: json,
});
});
And also you first create new state named as Items such as below.
this.state = {
Items: []
};
And finally Iterate on Items.
BR

Node Elasticsearch module search not returning results

I'm setting up a project with node (v 12.4.0) and elasticsearch (7.4.0) using the official module.
I'm attempting to search using
import { Client, RequestParams, ApiResponse } from '#elastic/elasticsearch'
const client = new Client({ node: 'http://localhost:9200' })
const params: RequestParams.Search = { index: 'doc', body: { query: { match: { title: "castle" } } } };
const response: ApiResponse = await client.search(params);
This gives a 200 response, but no results.
Attempting the same thing using Postman returns the 1 result.
POST http://localhost:9200/doc/_search
{
"query": {
"match": { "title": "castle" }
}
}
I'm not having any luck figuring out why the search function is not working. I've also tested get, add, and delete, which all work.
To create the index, I used:
await client.indices.create({ index: "doc" });
To add a document, I use:
await client.index({
index: 'doc',
body: {
title: "Castle Title",
body: "This is text that is not the title."
}
});
What am I doing wrong?
I've tested this and it works, the only thing is that elasticsearch is near real-time searchable. You need to wait 1 second before the document becomes searchable.
Basically, if you are running a test or something, where you save the record just before searching you need to either:
wait for 1 second before searching
trigger a manual refresh https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-refresh.html
wait for it to be refreshed when saving https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-refresh.html

How to only send specific attribute of a list in NodeJs response

I'm sorry before, maybe this is a really basic question/issue but I've been stucked a while.
I've a API built use ExpressJs and Sequelize. I've successfully got the data, but I got an issue when trying to show all data as a list.
Here is my code in view to set response:
exports.ok = function (values, res) {
var data = {
'status': 200,
'values': values
};
res.json(data);
res.end();
}
the response showed as:
the data above show all attribute, how do I can show only name and id.
Thankyou.
As #Sindis suggested, you just need to apply map on the response and then select the required fields.
exports.ok = function (values, res) {
var data = {
'status': 200,
'values': values.map(val => return { id: val.id, name: val.name })
};
res.json(data);
res.end();
}
I hope it will help.
If you are using sequelize to get the result, you have to set attributes while querying the table. using like
const values = await db.Users.findAll({
attributes: ['id', 'name'],
order: [
['id', 'ASC']
]
});
SOLVED
It work with this:
exports.ok = function (values, res) {
var data = {
'status': 200,
'values': values.map(function (value) {
return {
id: value.id,
name: value.name,
email: value.email
}
})
};
res.type('json');
res.send(data);
};

Resources