How can i upload an image with graphql-upload - javascript

I tried uploading a file to a graphql server that has graphql-tool. I have set up the request multipart specification and I use Altair graphql client to make a request to the graphql endpoint.
I get the error SyntaxError: Unexpected token - in JSON at position 0
I do not know what I am doing incorrectly. Please help me out.
Below is my code
const graphqlHTTP = require('express-graphql');
const { graphqlUploadExpress } = require('graphql-upload');
const { makeExecutableSchema } = require('#graphql-tools/schema');
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
app.use("/graphql",
graphqlUploadExpress({ maxFileSize: 10000000, maxFiles: 10 }),
graphqlHTTP((req, res) => ({
schema,
graphiql: true,
context: {
accessToken: req.header("accessToken"),
authFunction: jwtAuthentication
},
tracing: true
})))
in my resolver, I included GraphQLUpload
module.exports = {
Upload: GraphQLUpload,
Query: {
},
Mutation: {
ChangeBusinesslogo: async (parent, { file }, context, info)=> {
//
},
}
}
In my type definition, I have
scalar Upload
type File {
id: ID!
path: String!
filename: String!
mimetype: String!
encoding: String!
}
type Mutation {
ChangeBusinesslogo(file: Upload!): File
}
I use altair graphql-client but I get this error
SyntaxError: Unexpected token - in JSON at position 0
I do not know what I am not doing correctly. Please help me out

Related

Shopify Template webhookHandlers Error Before Doing Anything

I have been trying to learn the basics of building a app for shopify. However I am running in to the issue that right from creating the template in my index.js file. I am not sure what is causing this error as I literally just created the app and have not edited any of the code or added anything. Any help on this would be appreciated, since this is a completely new skill I'm working on learning.
The error I am getting is:
Type '{ CUSTOMERS_DATA_REQUEST: { deliveryMethod: DeliveryMethod; callbackUrl: string; callback: (topic: any, shop: any, body: any, webhookId: any) => Promise<void>; }; CUSTOMERS_REDACT: { ...; }; SHOP_REDACT: { ...; }; }' is not assignable to type 'WebhookHandlersParam'.
Property 'CUSTOMERS_DATA_REQUEST' is incompatible with index signature.
Type '{ deliveryMethod: DeliveryMethod; callbackUrl: string; callback: (topic: any, shop: any, body: any, webhookId: any) => Promise<void>; }' is not assignable to type 'WebhookHandler | WebhookHandler[]'.
Type '{ deliveryMethod: DeliveryMethod; callbackUrl: string; callback: (topic: any, shop: any, body: any, webhookId: any) => Promise<void>; }' is not assignable to type 'HttpWebhookHandler'.
Types of property 'deliveryMethod' are incompatible.
Type 'DeliveryMethod' is not assignable to type 'DeliveryMethod.Http'.
index.js
// #ts-check
import { join } from "path";
import { readFileSync } from "fs";
import express from "express";
import serveStatic from "serve-static";
import shopify from "./shopify.js";
import productCreator from "./product-creator.js";
import GDPRWebhookHandlers from "./gdpr.js";
const PORT = parseInt(process.env.BACKEND_PORT || process.env.PORT, 10);
const STATIC_PATH =
process.env.NODE_ENV === "production"
? `${process.cwd()}/frontend/dist`
: `${process.cwd()}/frontend/`;
const app = express();
// Set up Shopify authentication and webhook handling
app.get(shopify.config.auth.path, shopify.auth.begin());
app.get(
shopify.config.auth.callbackPath,
shopify.auth.callback(),
shopify.redirectToShopifyOrAppRoot()
);
app.post(
shopify.config.webhooks.path,
shopify.processWebhooks({ webhookHandlers: GDPRWebhookHandlers })
);
// All endpoints after this point will require an active session
app.use("/api/*", shopify.validateAuthenticatedSession());
app.use(express.json());
app.get("/api/products/count", async (_req, res) => {
const countData = await shopify.api.rest.Product.count({
session: res.locals.shopify.session,
});
res.status(200).send(countData);
});
app.get("/api/products/create", async (_req, res) => {
let status = 200;
let error = null;
try {
await productCreator(res.locals.shopify.session);
} catch (e) {
console.log(`Failed to process products/create: ${e.message}`);
status = 500;
error = e.message;
}
res.status(status).send({ success: status === 200, error });
});
app.use(serveStatic(STATIC_PATH, { index: false }));
app.use("/*", shopify.ensureInstalledOnShop(), async (_req, res, _next) => {
return res
.status(200)
.set("Content-Type", "text/html")
.send(readFileSync(join(STATIC_PATH, "index.html")));
});
app.listen(PORT);

ValidationError: File validation failed: filename: Path `filename` is required., path: Path `path` is required

in this project, I try to upload a file. from frontend to backend, and save that file, the error showing like this,
error
the error
this.$__.validationError = new ValidationError(this);
^
ValidationError: File validation failed: filename: Path `filename` is required., path: Path `path` is required.
at model.Document.invalidate (C:\Users\harsh\Desktop\FILE-SHARING-APP\node_modules\mongoose\lib\document.js:2970:32)
at C:\Users\harsh\Desktop\FILE-SHARING-APP\node_modules\mongoose\lib\document.js:2759:17
at C:\Users\harsh\Desktop\FILE-SHARING-APP\node_modules\mongoose\lib\schematype.js:1333:9
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
errors: {
filename: ValidatorError: Path `filename` is required.
at validate (C:\Users\harsh\Desktop\FILE-SHARING-APP\node_modules\mongoose\lib\schematype.js:1330:13)
at SchemaString.SchemaType.doValidate (C:\Users\harsh\Desktop\FILE-SHARING-APP\node_modules\mongoose\lib\schematype.js:1314:7)
at C:\Users\harsh\Desktop\FILE-SHARING-APP\node_modules\mongoose\lib\document.js:2751:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: {
validator: [Function (anonymous)],
message: 'Path `filename` is required.',
type: 'required',
path: 'filename',
value: undefined
},
here , for unique file Name i used uuid and i given storege,
limit:{fileSize:100000*100},
the requirement is I need to upload any file and I generate the link for that file for download that file
fails.js
const router = require ('express').Router();
const multer = require('multer');
const path = require('path');
const File =require('../models/file');
const {v4 : uuid4} =require('uuid')
let storege = multer.diskStorage({
destination:(req,file,cd) =>cd(null,'uploads/'),
// for unique file Name
filename:(req,file,cb)=>{
const uniqueName =`${Date.now()}-${Math.round(Math.random()*1E9)}${this.path.extname(file.originalname)}`;
cb(null,uniqueName);
}
})
let upload =multer({
storege,
limit:{fileSize:100000*100},
}).single('myfiles');
router.post('/' ,(req,res)=>{
//store files:
upload(req,res,async(error)=>{
//validate require
if(!req.file){
return res.json({error:'All files are required.'})
}
if (error){
return res.status(500).send({error:error.message})
}
// store into Database:
const file = new File({
filename: req.file.filename,
uuid:uuid4(),
path:req.file.path,
size:req.file.size,
});
const response = await file.save();
return res.json({file:`${process.env.APP_BASE_URL}/files/${response.uuid}`});
//http://localhost:3000/files/2433r4r4t444r3-3r3r
});
//Respone ->Link
})
module.exports=router;
here is the mongoose. Schema has filename, path, size, uuid, sender and resiver is false
file.js
const mongoose = require ('mongoose');
const Schema =mongoose.Schema;
const filesSchema = new Schema({
filename:{type:String,required:true},
path:{type:String,required:true},
size:{type:Number,required:true},
uuid:{type:String,required:true},
sender:{type:String,required:false},
resiver:{type:String,required:false},
},{ timestamps:true});
module.exports=mongoose.model('File',filesSchema)
the error shows like :
my Requirement needs to upload any file means .jpg, png, or pdf.
this.$__.validationError = new ValidationError(this);
^
ValidationError: File validation failed: path: Path `path` is required.
how to fix this error,
I found out for myself what the error was. This is an error caused by a small mistake. the mistake is in fails.js
// for unique file Name
filename:(req,file,cb)=>{
const uniqueName =`${Date.now()}-${Math.round(Math.random()*1E9)}${this.path.extname(file.originalname)}`;
cb(null,uniqueName);
}
in this Piece of code has a problem. ${this.path.extname(file.originalname)};` here noneed to add this.path
only need to use ${path.extname(file.originalname)} Actually this is a mistake that came to me unknowingly.

How do I convert the code of creating a file to updating a file?

Is there a way to convert a create file code to an update file code. I'm new to coding Javascript and I need an example of this. I really want to find a way to update my old google drive files and make them much better.
const { google } = require('googleapis');
const path = require('path')
const fs = require('fs')
const CLIENT_ID = '898005425789-ie9c7s59ri74mmg6hp2iouamo3vrd09d.apps.googleusercontent.com';
const CLIENT_SECRET = 'qXCxqGgRH8woQG5wlK0WK79k';
const REDIRECT_URI = 'https://developers.google.com/oauthplayground';
const REFRESH_TOKEN =
'1//04SmYavGXSUwQCgYIARAAGAQSNwF-L9IrhcLntTl1298HgjIUvrmRauA81x-ZI9ddwg9h1C7Q0fzhqR2f1dvawTO3A00LoWy-V5g'
const oauth2Client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
REDIRECT_URI
);
oauth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });
const drive = google.drive({
version: 'v3',
auth: oauth2Client,
});
const filePath = path.join(__dirname, 'sus.jpg');
async function uploadFile() {
try {
const response = await drive.files.create({
requestBody: {
name: 'suseyes.jpg',
mimeType: 'image/jpg',
createdTime: "2017-03-13T05:51:43.030Z",
modifiedTime: "2018-07-21T05:51:43.030Z",
description: "hi",
filePath: '/upload/drive/v3/files/test/',
},
media: {
mimeType: 'image/jpg',
body: fs.createReadStream(filePath),
},
});
console.log(response.data);
} catch (error) {
console.log(error.message);
}
}
uploadFile();
I believe your goal and your current situation as follows.
You want to update the existing file using googleapis for Node.js.
The file is an image file (JPEG file).
From your script, I thought that you are using Node.js.
You have already been able to get and put values for the file on Google Drive using Drive API.
Modification points:
When the file is updated, createdTime cannot be updated. It seems that this is the current specification. When it tries to modify createdTime, an error like The resource body includes fields which are not directly writable. occurs.
When you want to update the file, it is required to include fileId in the request.
filePath: '/upload/drive/v3/files/test/' cannot be used in the request body.
When above points are reflected to your script, it becomes as follows.
Modified script:
From:
const response = await drive.files.create({
requestBody: {
name: 'suseyes.jpg',
mimeType: 'image/jpg',
createdTime: "2017-03-13T05:51:43.030Z",
modifiedTime: "2018-07-21T05:51:43.030Z",
description: "hi",
filePath: '/upload/drive/v3/files/test/',
},
media: {
mimeType: 'image/jpg',
body: fs.createReadStream(filePath),
},
});
To:
const fileId = "###"; // Please set the file ID of the file you want to update.
const filePath = "###"; // Please set the filename with the path.
const response = await drive.files.update(
{
fileId: fileId,
requestBody: {
name: "suseyes.jpg",
mimeType: "image/jpg",
// createdTime: "2017-03-13T05:51:43.030Z", // This cannot be included.
modifiedTime: "2018-07-21T05:51:43.030Z",
description: "hi",
},
media: {
mimeType: "image/jpg",
body: fs.createReadStream(filePath),
},
});
Note:
In this case, there might be the files you cannot update using the image file. So please be careful this.
Reference:
Files: update

How to access request headers in custom graphQL resolvers when using neo4j-graphql-js?

When trying:
const server = new ApolloServer({
schema: schema,
context: { req, driver, neo4jDatabase: process.env.NEO4J_DATABASE },
introspection: true,
playground: true,
})
error: req is not defined
and when trying:
const server = new ApolloServer({
schema: schema,
context: ({ res }, driver, neo4jDatabase = process.env.NEO4J_DATABASE) => (
res, driver, neo4jDatabase
),
introspection: true,
playground: true,
})
error: No Neo4j JavaScript driver instance provided.
I've already tried a lot of different ways of writing it and reading Apollo source code but no success.
Solved it thanks to this comment https://github.com/grand-stack/graphql-auth-directives/issues/4#issuecomment-494620480
const server = new ApolloServer({
schema,
context: ({ req }) => {
return {
headers: req.headers,
driver
};
}
});
and it did work.

upload and post a file from client (react js) to nodejs express server

From my client side I have this code, in react js componet I create this:
class PopinForm extends PureComponent {
constructor() {
super();
this.state = {
file : {},
isError : {
file : false,
}
};
}
//upload here
_handleUploadFile = () => {
uploadFile(this.state.file)
};
render() {
<Root>
<Input width="45%" type="file" onChange={ (e) => this.setState({file: e.target.files[0]}) } />
<ButtonPopin width="20%" onClick={this._handleUploadFile}>
Upload
</ButtonPopin>
</Root>
}
export default translate('translations')(PopinForm);
Then in my export module, this the function uploadFile:
export function uploadFile(file) {
fetch(`${apiUrl}/upload`, {
method: 'post',
headers: headers,
mode: 'cors',
cache: 'default',
resolveWithFullResponse: true,
body: file,
})
.then(request => request.post())
.catch((err) => {
console.error(`>>>>>>> an internal error occurred: ${JSON.stringify(err, null, 3)}`)
})
}
Using reactjs, I recover my file data from an input type file. This is my file when I made a console.log(file) :
File
lastModified: 1522422082000 ​
lastModifiedDate: Date
2018-03-30T15:01:22.000Z
​name: "test.xls" ​
size: 7105 ​
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ​
webkitRelativePath: ""
So it matches well with the right file I upload from the input type file.
But, on my server side I'am using multer and this is the method I use to recover the file, here the code in index.js:
// instantiate multer storage to define the tmp folder path to store file
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'tmp/')
},
// register the file with his original name and extension
filename: (req, file, cb) => {
cb(null, file.originalname)
},
})
// declare the upload method with storage path and filename registration
const upload = multer({storage: storage})
// upload XLSX massive request import
app.post('/upload', upload.single('uploadRequests'), require(path.join(__dirname, 'some', 'path', 'to', 'uploadRequest.js')))
WHen I submit the upload file I have this error: UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 12): TypeError: Cannot read property 'originalname' of undefined due to the request I made in the file uploadRequests.js here: const fileName = req.file.originalname
This is the code for uploadRequests.js:
const uploadRequests = async (req, res) => {
// get filename by req
const fileName = req.file.originalname
// instantiate excel class
const workbook = new Excel.Workbook()
workbook.xlsx.readFile(req.file.path)
.then(async () => {
// treatment on xlsx file test with postman exmaple and files, nothing went wrong here
// fetch on database request and CRUD method to update or create data
return res.json({message: 'massive import request success !', data: data})
})
.catch((err) => {
throw new Error(`workbook readFile method return an ${err}`)
})
}
module.exports = uploadRequests
I am new to nodejs, and I would like to know how properly recover my file from the client side on my nodejs server.

Categories