Custom Fields not showing on API return [Braintree] - braintree

I'm creating a customer like this using the official Node SDK :
const createCustomer = (email, body) =>
new Promise((resolve, reject) =>
gateway.customer.create(
{
email,
firstName: body.FirstName,
lastName: body.LastName,
paymentMethodNonce: body.Nonce,
customFields: {
countrycode: body.CountryCode
}
},
(err, result) => {
if (err) return reject(err);
return resolve(result.customer);
}
)
);
I have checked that body.CountryCode has a correct value.
When I enter in the Control Panel (Vault), I can see perfectly the country code like this:
But, when I try to get the customFields param from the API, is always an empty string:
I have configured the custom field in Store and Pass Back
(A Stored custom field will be stored with the transaction details and passed back.)
Where is the problem? Thanks.

Related

Next.js seems to cache files as in a route of _next/data/[path].json preventing getStaticProps from running in server side render

The issue appears to happen when I post the link on platforms like Discord and Slack, where then to produce a URL preview they send a request to the link. The link which in this case follows this structure (normal format) www.domain.com/ctg/[...ids].
Within [...ids] I either pass one of two ids for the same object, the object has the following structure:
type Catalogue {
id: ID!
edit_id: String!
user_id: String!
title: String
...
}
The first id I could pass into [...ids] would be Catalogue.id
The second id I could pass into [...ids] would be Catalogue.edit_id
Whenever either of those inputs for [...ids] is passed as part of a request the following getStaticProps is ran:
export const getStaticProps: GetStaticProps = async ({ params }) => {
const { ids } = params;
let catalogue: CatalogueType | null = await fetchFullCatalogue(ids[0]);
return {
props: {
catalogue_prop: catalogue,
params,
},
};
};
with fetchFullCatalogue being:
export const fetchFullCatalogue = async (
id: string
): Promise<CatalogueType | null> => {
let catalogue: CatalogueType;
const fetchToUrl =
process.env.NODE_ENV === "development"
? "http://localhost:4000/graphql"
: process.env.BACKEND_URL + "/graphql";
// create a axios fetch request to the http://localhost:4000/graphql
const query = `
<...SOME FRAGMENTS LATER...>
fragment AllCatalogueFields on Catalogue {
id
edit_id
user_id
status
title
description
views
header_image_url
header_color
author
profile_picture_url
event_date
location
created
updated
labels {
...AllLabelFields
}
listings {
...AllListingFields
}
}
query Catalogues($id: ID, $edit_id: String) {
catalogues(id: $id, edit_id: $edit_id) {
...AllCatalogueFields
}
}`;
const config: AxiosRequestConfig = {
method: "post",
url: fetchToUrl,
headers: {
"Content-Type": "application/json",
},
data: JSON.stringify({
query,
variables: { id: id, edit_id: id },
}),
};
let response = await axios(config);
if (response.data.errors) return null;
catalogue = response.data.data.catalogues[0];
console.log("catalogue", catalogue);
return catalogue;
};
The request it is making is to the following API endpoint
Query: {
catalogues: async (
_: null,
args: { id: string; edit_id: string }
): Promise<Catalogue[]> => {
let catalogues: Catalogue[];
// when both id and edit_are passed
if (args.id && args.edit_id) {
catalogues = await getFullCatalogues(args.id, "id", true);
// the following convoluted request is the result of
// me responding to the fact that only the edit_id was working
if (catalogues.length === 0) {
catalogues = await getFullCatalogues(args.edit_id, "edit_id", true);
if (catalogues.length === 0) {
throw new UserInputError("No catalogues found");
}
} else {
catalogues = await getFullCatalogues(
catalogues[0].edit_id,
"edit_id",
true
);
}
console.log("catalogues", catalogues);
} else if (args.id) {
catalogues = await getFullCatalogues(args.id);
} else if (args.edit_id) {
catalogues = await getFullCatalogues(args.edit_id, "edit_id");
} else {
const res = await db.query(fullCatalogueQuery());
catalogues = res.rows;
}
return catalogues;
},
...
},
This results in the following output within the deployed logs:
The logs show the data when the Catalogue is first created which simultaneously navigates me to the URL of "normal format" with Catalogue.id which is interpreted as /_next/data/qOrdpdpcJ0p6rEbV8eEfm/ctg/dab212a0-826f-42fb-ba21-6ebb3c1350de.json. This contains the default data when Catalogue is first generated with Catalogue.title being "Untitled List"
Before sending both requests I changed the Catalogue.title to "asd".
Notice how the request with the Catalogue.edit_id which was sent as the "normal format" was interpreted as /ctg/ee0dc1d7-5458-4232-b208-1cbf529cbf4f?edit=true. This resulted in the correct data being returned with Catalogue.title being "asd".
Yet the following request with the Catalogue.id although being of the same "normal format" never provoked any logs.
(I have tried sending the request without the params ?edit=true and the same happens)
Another important detail is that the (faulty) request with the Catalogue.id produces the (faulty) URL preview much faster than the request with Catalogue.edit_id.
My best theory as to why this is happening is that the data of the URL with Catalogue.id is somehow stored/cached. This would happen as the Catalogue is first created. In turn it would result in the old stored Catalogue.id being returned instead of making the fetch again. Whereas the Catalogue.edit_id makes the fetch again.
Refrences:
Live site: https://www.kuoly.com/
Client: https://github.com/CakeCrusher/kuoly-client
Backend: https://github.com/CakeCrusher/kuoly-backend
Anything helps, I felt like ive tried everything under the sun, thanks in advance!
I learned that For my purposes I had to use getServerSideProps instead of getStaticProps

Not getting any data from api controller into vue component

I have a component in vue 3 named index which gets the user form data and passes it onto api controller in laravel.
async submitForm() {
try {
await axios.post(
"/api/show",
{
firstname: this.form.firstname,
email: this.form.email,
},
);
} catch (error) {
console.error("error");
}
},
and I'm trying to fetch the data sent into the controller via following method onto another component named show and all I'm getting is empty string and I don't understand the reason. Any guide would be really appreciated.
loadProductDetails() {
axios.post("api/show")
.then(({data}) => (this.products = data));
},
Solved the issue. It was because I was trying to get response from two different routes but the first one was already fetching the post response data and second one was returning the empty string and replacing the data I already recieved from the response.
try {
axios
.post("/api/show", {
firstname: this.form.firstname,
email: this.form.email,
selectedAnswer: this.form.selectedAnswer,
selectedCategory: this.form.selectedCategory,
})
.then((res) => {
localStorage.setItem("show", JSON.stringify(res.data));
});
} catch (error) {
console.error("error");
}
Simply saving the response data into local storage and getting it from another component solved the issue.
loadProductDetails() {
this.products = JSON.parse(localStorage.getItem('show'));
}

GraphQL (WP) get a custom post by uri

I'm following one of the tutorials on youtube on performing basic query on headless wordpress api with GraphQL. The query that the tutorial (over a year old now) does is:
query getBookBySlug($slug: String) {
book: bookBy(uri: $slug) {
title
book_meta{
price
publisher
}
}
}
Books/book is a custom pust type and I can query it using the GraphiQL playground in wordpress to see what it returns
The problem with the query above is that ir returns null. Also, the bookBy (or postBy) is apprently deprecated (according to the warning I get in GraphiQL suggesting instead post(id: "") or book(id: "") in my case. The problem is that I want to query the book by ''uri'' not ''id'' and there seems to be no option to query:
book(uri: "")
the only option seems:
book(id: "")
The uri field exists and is populated. This query in the GraphiQL returns successfully all the required book details:
query getBook {
book(id: "cG9zdDo0MA==") {
title
slug
uri
book_meta {
price
}
}
}
How can I change the first function to query a book by uri?
The query getBookBySlug has arguments declared somewhere your code (there must be to build the full schema). You need to change those arguments to accept uri instead of id.
Also the function that receives those arguments and returns the books must be able to handle the uri argument and find the correct book in the DB.
I used slug with nuxtjs
async asyncData({ params }) {
const data = {
query: `query GET_POST($slug: String) {
postBy(slug: $slug) {
title
content
author {
node {
name
}
}
featuredImage {
node {
caption
altText
sourceUrl(size: LARGE)
}
}
date
}
}`,
variables: {
slug: params.slug
}
}
const options = {
method: 'POST',
headers: { 'content-type': 'application/json' },
data: data,
url: 'http://localhost/graphql'
};
try {
const response = await axios(options);
return {
loadedPost: response.data.data.postBy
}
} catch (error) {
console.error(error);
}
},
here is what worked for me:
https://github.com/atazmin/nuxtjs-wordpress/blob/master/nuxt/pages/posts/_slug/index.vue

TypeORM - Retrieve data through relation query in resolver

So I'm trying to retrieve elements out of a join relation in an Apollo resolver.
I've got a User table, a Notification table. And a Relation table named:
notification_recipients_user defined by a ManyToMany relation on both entity but hosted on Notification :
//entity/Notification.ts
#ManyToMany(type => User, recipient => recipient.notifications)
#JoinTable()
recipients: User[];
I can create relation without problem through this mutation :
addNotificationForUser: async (_, { id, data }) => {
const user = await User.findOne({ id });
if (user) {
const notification = await Notification.create({
template: data,
recipients: [user]
}).save()
return notification;
} else {
throw new Error("User does not exists!");
}
}
However I'm totally not succeeding in retrieving data for a specific User.
allNotificationsOfUser: (_, { user }, ___) => {
return Notification.find({
where: { userId: user },
relations: ['recipients'],
})
The method find is one of TypeORM native methods.
However I must be doing something wrong because it react as if there wasn't any filter.
Okay so the best way of doing it is by using relation between entity.
So to get Notification you'll go by User.notifications
allUnseenNotificationsOfUser: async (_, { userId }, __) => {
const user = await User.findOne({
relations: ["notifications"],
where: { id: userId }
});
if (user) {
const notifications = user.notifications.filter(notification => !notification.seen)
return notifications;
}
return null;
}
And for the record for anyone stumbeling upon this you can use filter on your result to do a query like resolver.
const notifications = user.notifications.filter(notification => !notification.seen)
It feels tricky but works like a charm.

VueJS: Is there an easy way to validate email and password on client side based on the server side's validator?

I'm new to VueJS. I'm creating signup and login page and users are supposed to send the email and password to the back-end (I'm using Django) to check if the data is valid. I'd like to show error messages on form if one of them are not valid.
I saw some documentation about validation and seems like I have to write a bunch of validation code. Now I'm wondering if there's an easy way to do it.
I'd like to validate them based on the server side's validators.
Login.vue
export default {
data() {
return {
form: {
email: '',
password: '',
}
}
},
methods: {
onSubmit(event) {
event.preventDefault()
// validate the inputs here and shows error messages if they are not valid
const path = `http://127.0.0.1:8000/users/login/`
axios.post(path, this.form).then((resp) => {
location.href = '/'
})
.catch((err) => {
console.log(err)
})
}
}
}
Can anyone give me tips?
Yes, Here is the code you can follow.
In data make a reg object like this.
data(){
return{
email:null,
reg: /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,24}))$/
}
},
add then in your submit method
if(this.email == null || this.email == '')
{
this.errorEmail = "Please Enter Email";
}
else if(!this.reg.test(this.email))
{
this.errorEmail = "Please Enter Correct Email";
}

Resources