Image Upload Issue using strapi.connections.default.raw in Strapi - strapi

in Strapi cms, I need to upload images in the Strapi controller directly.
so I tried to use raw of Strapi, but ? symbol got replaced with $1 in the image URL.
const imageName = 'image name';
const imageHash = 'image hash value';
const imageExt = 'JPG';
const mimeExt= 'mimeExt';
const imageUrl = 'https://images.unsplash.com/photo-1518989229647-6377f907a0b2?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwxNjcxOTl8MHwxfHNlYXJjaHwxfHxuY2FhfGVufDB8MHx8fDE2NDY4NDg3ODI&ixlib=rb-1.2.1&q=80&w=1080';
const queryUpload = `INSERT INTO upload_file (name, hash, ext, mime, size, provider, url) values ('${imageName}','${imageHash}', '${imageExt}','image/${mimeExt}',23.4,'aws-s3','${imageUrl}') RETURNING id`;
const uploadFileResponse = await strapi.connections.default.raw(queryUpload);
...
Could you let me know if you have any solution to fix this issue?
Thanks

Related

React redux useSelector best practice

Learning redux/react-redux, I'm using useSelector with inner selector function in a separate file. It's working perfectly but I have question about best practices.
Assuming that I have a state with 3 entries (firstname, lastname, email), is it better to :
1. Have a specific selector for each case?
selector.js
export const selectFirstname = (state) => state.currentUser.firstName
export const selectLastname = (state) => state.currentUser.lastName
export const selectEmail = (state) => state.currentUser.email
component.js
const firstName = useSelector(selectFirstname)
const lastName = useSelector(selectLastname )
const email = useSelector(selectEmail)
2. Have a generic selector with param?
selector.js
export const selectItem = (key) => {
return (state) => state.currentUser[key]
}
component.js
const firstName = useSelector(selectItem('firstName'))
const lastName = useSelector(selectItem('lastName'))
const email = useSelector(selectItem('email'))
3. Have a global selector and use it with destructuring in my component?
selector.js
export const selectItem = (state) => state.currentUser
component.jsx
const {firstName, lastName, email} = useSelector(selectItem)
Thank you in advance
No, you shouldn't be doing #3. You should be returning the smallest amounts of data per the docs: https://redux.js.org/tutorials/fundamentals/part-5-ui-react#using-multiple-selectors-in-a-component
So 1 or 2 is your best option. Also, anytime currentUser changes the whole thing will re-render and if you are only using 3 of the values, why re-render the component when the values have not changed.

Parse Server - Get Pinned Object using Labels

I am storing objects in the Local Datastore via Pinning. I can pin objects under a label (e.g. following). If I want to return all of the people that a user is following there doesn't seem to be a way to do that. I can't even find a way to return all pinned objects regardless of their label. Am I missing something?
Here is my code for storing a person object in my Local Datastore:
peer.pinWithName( 'Followed' );
I can find out if the peer is followed using:
const Followed = Parse.Object.extend( 'Peer' );
const query = new Parse.Query( Followed );
query.fromLocalDatastore();
response = await query.get( peer.id );
Querying all objects from local data store
const Followed = Parse.Object.extend('Peer');
const query = new Parse.Query(Followed);
query.fromLocalDatastore();
response = await query.find();
Reference: https://docs.parseplatform.org/js/guide/#querying-the-local-datastore
Querying an object from pin with name
const Followed = Parse.Object.extend('Peer');
const query = new Parse.Query(Followed);
query.fromPinWithName('Followed');
response = await query.get(peer.id);
Querying all objects from pin with name
const Followed = Parse.Object.extend('Peer');
const query = new Parse.Query(Followed);
query.fromPinWithName('Followed');
response = await query.find();
Reference: http://parseplatform.org/Parse-SDK-JS/api/2.7.0/Parse.Query.html#fromPinWithName

Xero-node get invoice as PDF

I am trying to create an invoice in xero and then get a pdf version uploaded onto mongoDB through my parse server.
I am authenicating xero in an express app in the main.js of my application.
When I save the invoice Pdf to parse it is rejected as 'schema mismatch, expecting file but getting object', what am I missing in my code to create the PDF version?
let oauth_verifier = req.query.oauth_verifier;
let accessToken = await xeroClient.oauth1Client.swapRequestTokenforAccessToken(lastRequestToken, oauth_verifier)
.then(async() => {
var invoice = xeroClient.invoices.create(data)
.then(async(invoice) => {
var inv = invoice["Invoices"][0];
var invId = inv["InvoiceID"];
await xeroClient.invoices.get({ InvoiceID: invId}, "application/pdf")
.then((invPdf) => {
Parse.initialize("--------------------");
Parse.serverURL = 'http://--.---.---.--:--/parse';
var Invoices = Parse.Object.extend("Invoices");
var invoice = new Invoices;
invoice.set('invoicePdf', invPdf);
invoice.save();
event.returnValue = true;
win.close();
})
})
In the GitHub source for the Node.JS, there is a separate function called savePDF which seems to do the trick, as you noted in the comments above. https://github.com/XeroAPI/xero-node/blob/36ab8a513263426a173633691f5308237f473b99/src/AccountingAPIClient.ts#L469

to update the data I need to reload the page, how can I avoid this?

I have an application that saves the user in localStorage, I have checks for the existence of user on localStorage
componentDidMount(): void {
const {getNotes,} = this.props;
const userDataJSON = localStorage.getItem('userData');
if (userDataJSON) {
const {userID, sessionID,} = JSON.parse(userDataJSON);
return getNotes({sessionID, userID,});
}
}
but i have same checks in other blocks of code and i decide do it in utils
const userDataJSON = localStorage.getItem('userData');
export const userID = userDataJSON ? JSON.parse(userDataJSON).userID : null;
export const sessionID = userDataJSON ? JSON.parse(userDataJSON).sessionID : null;
export const username = userDataJSON ? JSON.parse(userDataJSON).username : '';
but data doesn't refresh when i logout and login in same session, i need reload page to correct work, how to refresh variables without reload page?
when i don't use utils all work good.
What's happening is that the code you are exporting on utils is only executed once (on initial load), because you are only storing the value in that moment, you could change those to be functions like this:
export const getUserData = () => {
const data = localStorage.getItem('userData');
return JSON.parse(data);
};
And you then when you use it, it will get the current value each time
const {userID, sessionID, username} = getUserData();
Another approach to avoid checking local storage each time you need the value could be to update the value on your state when modified and bring from local storage on initial mount, like this:
constructor(props) {
super(props);
this.state = getUserData();
}
updateUsername(username) {
this.setState({ username });
setUserData({ username }); // Assuming this one
}

wtforms, ndb and blobstore

I have this model:
class Product(ndb.Model):
title = ndb.StringProperty()
description = ndb.TextProperty()
img = ndb.BlobKeyProperty(indexed=False)
I need a html form that reads the values ​​of fields (title and description) and read the image (from a file field), and keeps the values ​​NDB object, the image in the Blobstore and updates the field BlobKeyProperty correctly.
As I work with wtforms, I tried to do it with a form like the following:
class ProductForm(Form):
title = fields.TextField('Title', [validators.Required(), validators.Length(min=4, max=25)])
description = fields.TextAreaField('Description')
img = fields.FileField('img')
The form shows the file field correctly but in the POST, it does not work because I don't know how to read the file, save the file to Blobstore and update the BlobKeyProperty.
My handler is this:
class ProductHandler(BaseHandler):
def new(self):
if self.request.POST:
data = ProductForm(self.request.POST)
if data.validate():
model = Product()
data.populate_obj(model)
model.put()
self.add_message("Product add!", 'success')
return self.redirect_to("product-list")
else:
self.add_message("Product not add!", 'error')
params = {
'form': ProductForm(),
"kind": "product",
}
return self.render_template('admin/new.html', **params)
Error is Expected str, got u'image.jpg'
If someone can help me, I would appreciate it!
The only solution I found is to use a deprecated low-level API described in https://developers.google.com/appengine/docs/python/blobstore/#Python_Writing_files_to_the_Blobstore
I make a wtform validator for the FileField.
I changed:
img = fields.FileField('img')
To:
img = fields.FileField('img', [create_upload_file])
And I write this validator:
def create_upload_file(form, field):
file_name = files.blobstore.create(mime_type=field.data.type, _blobinfo_uploaded_filename=field.data.filename)
with files.open(file_name, 'a') as f:
f.write(field.data.file.read())
files.finalize(file_name)
blob_key = files.blobstore.get_blob_key(file_name)
field.data = blob_key
The validator create the blob in blobstore, and then it change the field data from FieldStorage to blob_key.
I don't think that is the best solution but it works for now.

Resources