apollo server receive empty object from apollo upload client - apollo

I using apollo server and apollo upload client.
this is my client code to send file :
const updateMarketing = gql`
mutation UpdateMarketing(
$file1: Upload
$file2: Upload
$file3: Upload
$payload: MarketingInput!
) {
updateMarketing(
file1: $file1
file2: $file2
file3: $file3
payload: $payload
) {
isSuccess
error
data
}
}
`;
and this code for mutation :
<Mutation mutation={updateMarketing}>
{(
updateMarketing,
{ data, loading, error }
) => (
<div>
<form
onSubmit={e => {
e.preventDefault();
console.log(e.target.file1.files[0]);
updateWmsSkuTicketMarketing({
variables: {
file1: e.target.file1.files[0],
file2: e.target.file2.files[0],
file3: e.target.file3.files[0],
payload: {
id: e.target.id.value,
jobId: e.target.jobId.value
}
}
});
}}
>
<input
type="text"
id="id"
name="id"
placeholder="id"
/>
<br />
<input
type="text"
id="jobId"
name="jobId"
placeholder="job id"
/>
<br />
<input
type="file"
id="file1"
name="file1"
/>
<br />
<input
type="file"
id="file2"
name="file2"
/>
<br />
<input
type="file"
id="file3"
name="file3"
/>
<br />
<button type="submit">
update marketing
</button>
</form>
{loading && (
<div>Updating for marketing</div>
)}
{data && (
<div>
Update markting Proccess
is finished
</div>
)}
{error && (
<div>
Error update marketing…
</div>
)}
</div>
)}
</Mutation>
on server I tried to get the file :
const updateMarketing = ({ payload, token, file1, file2, file3 }) =>
new Promise((resolve, reject) => {
try {
console.log(file1, payload);
file1
.then(({ stream, filename }) => {
//get stream
});
}
// catch
but it error : file1.then is not a function
and console.log(file1) on server : {}
may be I wrong in client, but I dont find it.
please help me, where I wrong and how to fix it?

Does updateMarketing is the resolver?
Your mutation args are in second resolver function argument
In example of apollo upload client, it use second argument to get files too.
See docs
And the example

Related

How to solve problem "Must be a valid json" - Django + Vue js

I try to create object in Django with vue js + axios but somehowe this not work for me. I try in two ways and always I see in vue dev tools empty data. When I fill the data model in vuedev tools I see "Invalid value "Must be a valid Json"".
First way. I create a view that return jsonresponse.
#login_required
def save_embed(request):
if request.method == "POST":
form = SubmitEmbed(request.POST)
if form.is_valid():
url = form.cleaned_data['url']
r = requests.get('http://iframe.ly/api/oembed?url='+ url + '&api_key=' + IFRAMELYKEY)
data = r.json()
serializer = EmbedSerializer(data=data, context={'request': request})
if serializer.is_valid():
embed = serializer.save()
return JsonResponse(serializer.data, status=201, content_type="application/json", safe=False)
return JsonResponse(serializer.errors, status=400)
else:
form = SubmitEmbed()
return render(request, 'embed/embedadd.html', {'form': form})
Template:
<script>
new Vue({
el: '#app',
delimiters: ['!!', '!!'],
data () {
return {
url: "http://example.com"
}
},
methods: {
formSubmit(e) {
e.preventDefault();
let currentObj = this;
this.axios.post('http://wege.local:8000/recipes/recipe/embed/add/', {
url: this.url,
})
.then(function (response) {
currentObj.output = response.data;
})
.catch(function (error) {
currentObj.output = error;
});
}
}
});
</script>
Form:
<div id="app">
!! url.title !!
<form method="post" class="margin-bottom-25" #submit="formSubmit">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-success-gradiant">Dodaj link</button>
</form>
</div>
In the url field has been added v-model "url".
as you can see in the screenshot below, when I fill in the url field, nothing happend
Second way is to create endpoint with rest framework in Django and then create templateview with code:
<div id="app">
<form method="post" class="margin-bottom-25" #submit="formSubmit">
{% csrf_token %}
<div class="form-group">
<label for="formGroupExampleInput">Adres przepisu*</label>
<input type="url" class="form-control" id="formGroupExampleInput" placeholder="Url" v-model="embed.url">
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Tytuł</label>
<input class="form-control" id="formGroupExampleInput2" placeholder="Title" v-model="embed.title">
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Description</label>
<input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Description" v-model="embed.description">
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Thumbnail_url</label>
<input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Tthumbnail_url" v-model="embed.thumbnail_url">
</div>
<button type="submit" class="btn btn-success-gradiant">Dodaj link</button>
</form>
!! embed.title !!
!! embed.url !!
</div>
Vue js:
<script>
new Vue({
el: '#app',
delimiters: ['!!', '!!'],
data () {
return {
embed:{
url: 'http://example.com',
title: '',
description: '',
thumbnail_url: '',
}
}
},
methods: {
formSubmit(e) {
e.preventDefault();
let currentObj = this;
this.axios.post('http://wege.local:8000/recipes/embeds/', this.embed)
.then(function (response) {
currentObj.output = response.data;
})
.catch(function (error) {
currentObj.output = error;
});
}
}
});
</script>
In the second case the same problem, in vue tools the fields are still empty after completing the form.
I think your response is okay.
When/where do you define or gloabally bind axios to this? You keep trying this.axios, which does not exist. More on Vue instance properties here.
Unless I'm missing where you bind this.axios...
You need to import axios from "axios"; and do axios.post(...)
To see if your request is going out, try looking at the network tab in dev tools and see the requests that go out with the data! I see you're using firefox, check out the docs here

How to fix "net::ERR_CONNECTION_REFUSED and Error: Network Error" error in Reactjs,Django,Django Rest Frame work project

I am trying pass data from reactjs to django through django rest api by post method but there raising this problem.
I have tested post method through Django-REST Api GUI.It's working perfectly.
My Reactjs component code:
import React, { Component } from 'react'
import './Register.css';
import axios from 'axios'
const REGISTER_URL = 'http://127.0.0.1:8000/api/register/?format=json' // received api ulr...
const initiaState = {
username : '',
email : '',
password: ''
}
class Register extends Component{
constructor(){
super()
this.myRegister = React.createRef()
}
state = {
...initiaState
}
changeHandler = (event) => {
this.setState({
[event.target.name]: event.target.value
})
}
submitHandler = (event) =>{
event.preventDefault()
console.log(this.state)
this.myRegister.current.reset()
this.setState({
...initiaState
});
axios.post(REGISTER_URL,this.state)
.then(res =>{
console.log(res)
})
.catch(error =>{
console.log("ERROR::: "+error)
})
}
render(){
return(
<div className="Register-box">
<form ref = {this.myRegister} className="Form" onSubmit={this.submitHandler }>
<div className ="form-group ">
<label htmlFor="username" > Name: </label>
<input
className = "from-control ml-4"
type="text"
placeholder = ' Enter Your Name '
name = "username"
id = "username"
value = {this.state.name}
onChange = {this.changeHandler}
/>
</div>
<div className ="form-group">
<label htmlFor="email" > Email: </label>
<input
className = "from-control ml-4"
type="text"
placeholder = ' Enter Your Email '
name = "email"
id = "email"
value = {this.state.email}
onChange = {this.changeHandler}
/>
</div>
<div className ="form-group">
<label htmlFor="password" className="mr-4"> Password: </label>
<input
className = "from-control ml-2"
type="password"
placeholder = ' Enter Your Password '
name = "password"
id = "password"
value = {this.state.password}
onChange = {this.changeHandler}
/>
</div>
<button className = "btn btn-primary" type="submit" value="Submit"> Submit </button>
</form>
</div>
);
}
}
export default Register;
The error is the server connection error. Make sure you have run your server properly.
Check your IP address is correct or not
As you are running your Django server as debugging/testing mode. Run your server using python manage.py runserver 0.0.0.0:8000 here 8000 is the port number.

semantic-ui-react form validation with Yup

I read this solution but that doesn't really answer the question. I am using formik and semantic-ui-react.
Is is possible to use Yup with semantic-ui-react?
If yes could someone provide an example?
yes it is possible , Here is one way to do it. paste this code in codesandbox.io and install the dependencies like formik yup and semantic-ui-react
import React from "react";
import { render } from "react-dom";
import { Formik, Field } from "formik";
import * as yup from "yup";
import { Button, Checkbox, Form } from "semantic-ui-react";
const styles = {
fontFamily: "sans-serif",
textAlign: "center"
};
const App = () => (
<>
<Formik
initialValues={{
firstname: "",
lastname: ""
}}
onSubmit={values => {
alert(JSON.stringify(values));
}}
validationSchema={yup.object().shape({
firstname: yup.string().required("This field is required"),
lastname: yup.string().required()
})}
render={({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit
}) => {
return (
<Form>
<Form.Field>
<label>First Name</label>
<input
placeholder="First Name"
name="firstname"
onChange={handleChange}
onBlur={handleBlur}
/>
</Form.Field>
{touched.firstname && errors.firstname && (
<div> {errors.firstname}</div>
)}
<Form.Field>
<label>Last Name</label>
<input
placeholder="Last Name"
name="lastname"
onChange={handleChange}
onBlur={handleBlur}
/>
</Form.Field>
{touched.lastname && errors.lastname && (
<div> {errors.lastname}</div>
)}
<Form.Field>
<Checkbox label="I agree to the Terms and Conditions" />
</Form.Field>
<Button type="submit" onClick={handleSubmit}>
Submit
</Button>
</Form>
);
}}
/>
</>
);
render(<App />, document.getElementById("root"));

Submitting a video or image to Facebook using blueimp/jQuery-File-Upload

I have racked my brains all day today trying to get this post to work. Basically I am using the blueimp JQuery-File-Upload code and I have a page with the styled input button that selects a file from the file system - an image or a video.
<span class="button fileinput-button">
<i class="fa fa-plus" aria-hidden = "true"></i>
Add Photo or Video
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]" />
</span>
I also coded into the page a form with data that is needed for the Facebook post of the image or video.
<form id = "fb-form" enctype="multipart/form-data" method="post" name="fileinfo">
<!---->
<input type="hidden" name="access_token" value="<AN ACCESS TOKEN>">
<input type="hidden" name="title" value="My fabulous title" />
<input type="hidden" name="description" value="I made this movie with my own hands" />
<input type="hidden" name="name" value="My Challenge Movie" />
<input type="hidden" name="scope" value="publish_stream" />
<input type="hidden" name="app_id" value="<APP_ID>" />
<input type="hidden" name="debug" value="all" />
</form>
My javascript that I have customised is shown here in a fragment
$('#fileupload').fileupload({
url: url,
acceptFileTypes: /(\.|\/)(mp3|ogg|mp4|mov|flv|gif|jpe?g|png)$/i,
dataType : 'json',
autoUpload : false,
singleFileUploads : true,
multipart : true,
type : 'POST',
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 425,
previewMaxHeight: 600
}).on('fileuploadadd', function (e, data) {
$("#files").empty(); // to remove the canvas when a new pic is selected
$('progress').attr('value', 0);
$scope.$apply(function (response) {
$scope.image_chosen = true;
});
if(data.originalFiles[0]) {
if(data.originalFiles[0]) {
$('#fileupload').fileupload(
'option',
{
url: 'https://graph-video.facebook.com/v2.8/140954354354343/videos',
formData: $('#fb-form').serializeArray()
}
);
}
}
data.context = $('<div/>').appendTo('#files');
data.context.addClass('fix-position');
var file = data.files[0], index = 0;
var node = $('<p/>').append(uploadButton.clone(true).data(data));
node.appendTo(data.context);
})
Basically I am getting for images a :
{
"error": {
"message": "An access token is required to request this resource.",
"type": "OAuthException",
"code": 104,
"fbtrace_id": "GdH43Db1ziy"
}
}
and for videos:
{
"error": {
"message": "There was a problem uploading your video file. Please try again.",
"type": "OAuthException",
"code": 381,
"error_subcode": 1363021,
"is_transient": false,
"error_user_title": "Video Upload Problem",
"error_user_msg": "There was a problem uploading your video. Please try again.",
"fbtrace_id": "EnIrs+2K2uN"
},
"__debug__": {}
}
But the Access Token has been validated through the API explorer...
I have tried doing the upload using just HTML form elements and submitting from the page without JS and it works - so I am kind of thinking it is something to do with the JS XHR request...
Does anyone have any experience or ideas?

Check if is a valid URL that ends in .jpg, .png, or .gif in wordpress post content

I'm doing a front end form to let users submit a URL that is valid but also is an image, ending with .jpg, .png, or .gif.
This is my form:
<form action="" id="primaryPostForm" method="POST">
<fieldset>
<p>Accepting GIF/JPG/PNG URL (Max size: 3MB)</p>
<label for="postTitle"><?php _e('* POST TITLE:', 'framework') ?></label>
<input type="text" name="postTitle" id="postTitle" class="required" value="<?php if ( isset( $_POST['postTitle'] ) ) echo $_POST['postTitle']; ?>" />
</fieldset>
<fieldset>
<label for="postContent"><?php _e('* URL:', 'framework') ?></label>
<textarea name="postContent" id="postContent" class="required" <?php if ( isset( $_POST['postContent'] ) ) { if ( function_exists( 'stripslashes' ) ) { echo stripslashes( $_POST['postContent'] ); } else { echo $_POST['postContent']; } } ?>></textarea>
</fieldset>
<fieldset>
<input type="hidden" name="submitted" id="submitted" value="true" />
<button type="submit"><?php _e('SUBMIT', 'framework') ?></button>
</fieldset>
</form>
This is how i get the INFO and create the post :
if ( isset( $_POST['submitted'] ) && isset( $_POST['post_nonce_field'] ) && wp_verify_nonce( $_POST['post_nonce_field'], 'post_nonce' ) ) {
$post_information = array(
'post_title' => wp_strip_all_tags( $_POST['postTitle'] ),
'post_content' => $_POST['postContent'],
'post_type' => 'post',
'post_status' => 'publish'
);
$new_post = wp_insert_post( $post_information );
I would like to check if characters inserted in the post_content match a URL that ends in .jpg/png/gif and from that point create a conditional tag like this :
if $_POST['postContent'] == URL THAT ENDS in JPG/PNG/GIF {
do something }
How can i accomplish this?
Here's a basic match for a URL along with your jpg/png/gif option at the end:
\b(https?|ftp|file)://[-A-Z0-9+&##/%?=~_|$!:,.;]*[A-Z0-9+&##/%=~_|$]\.(?:jpg|png|gif)\b
This rings alarm bells in my mind though, it could potentially be a security risk, if someone wanted to inject some kind of code into this form, they might be able to.
Hopefully your code can tell the difference between an image and a script.