Unable to upload image from RN app to meteor backend - meteor

I want to upload image from my RN app to meteor backend. I am using "react-native-image-picker": "^0.26.7" for getting imagefile from gallery or camera and uploading to meteor using package react-native-meteor to collectionFs this is my code of RN app where I am calling meteor method for image upload as soon as user select image:
_handleSelectFile() {
const { order } = this.state;
var options = {
title: 'Select Avatar',
storageOptions: {
skipBackup: true,
path: 'images'
}
};
ImagePicker.showImagePicker(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else {
// let source = { uri: response.uri };
// You can also display the image using data:
let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
order: {
...order,
fileName: response.fileName
}
});
let fileData = response.data;
// const body = new FormData();
// body.append('file',fileData);
var photo = {
url: fileData,
type: 'image/jpeg',
name: 'photo.jpg',
};
Meteor.FSCollection('orderImages').insert(photo, function (err, res) {
if (err) {
console.log('error during uploading');
} else {
console.log('uploading successfully');
// _this.props.navigator.pop();
}
});
}
});
}
and this is my server side code:
export const Orders = new Mongo.Collection('orders');
export const OrderImages = new FS.Collection("orderImages", {
filter: {
maxSize: 1048576,
allow: {
contentTypes: ['image/*'],
}
},
stores: [new FS.Store.FileSystem("orderImages")]
});
if (Meteor.isServer) {
OrderImages.allow({
insert: function () {
return true;
}
});
}
and I am getting error like this:
ExceptionsManager.js:65
Cannot read property 'apply' of undefined

Related

Retrieve data from the firebase dynamic link

Im trying to get the data from the generated firebase dynamic link.
I passed Id while generating the dynamic link. I need to get the particular id from the generated dynamic link. Can you please help me.
Where it generates link as :https://thejyotistore.page.link/jNngseAasXzE5SuSA
const ShareLink = ({
fallbackUrl, id, product }) =>
{
const buildLink = async () =>
{
let link = await axios({
method: "POST",
url:
`https://firebasedynamiclinks
.googleapis.com/v1/shortLinks?
key=AIzaSyDNZvtkjAqf8c9esg
gSEzV2 L7. 3vEUv1FfQ`,
headers: {
"Content-Type":
"application/json",
},
data: {
dynamicLinkInfo: {
domainUriPrefix: `https://thejyotistore.page.link`,
link: `https://youtube.com/${id}`,
androidInfo: {
androidPackageName: "com.jyotistore.main",
},
},
},
});
if (link.status === 200 && link.data.hasOwnProperty("shortLink")) {
console.log(link.data.shortLink);
return link.data.shortLink;
}
};
const shareLink = async () =>
{
let shareUrl;
try {
shareUrl = await buildLink();
console.log(shareUrl);
} catch (error) {
console.log(error);
}
try {
if (shareUrl !== "") {
const result = await Share.share({
message: `Hey, ${"\n \n"}I would like to invite you to check out this New App from Jyoti Store. ${"\n \n"} ${product}Download the App now: ${"\n \n"} ${shareUrl}`,
});
}
} catch (error) {
console.log(error);
}
};

Get content related to a user in Strapi

I have a collection in Strapi called projects and I want to be able to fetch only the projects belonging to the currently logged in user. I'm using Next.js with NextAuth on the frontend and I'm currently filtering the results using:
/api/projects?filters[user][id][$eq]=${session.id}
This works fine except the endpoint still allows a user to fetch projects for all users if accessed directly. I'm thinking a better approach would be to setup a custom API endpoint in Strapi which would be something like /api/projects/:user. Is this the best way to acheive this? I've managed to setup a custom endpoint in Strapi using the CLI but I'm not sure what logic needs to go in the controller. Would modifiying an exisiting endpoint be better?
Any advice appreciated, thanks!
Custom endpoint create is good idea. I had same problem. Once i created custom endpoint then i got data with entitiyservice. It's work. Below image is my code.
./scr/api/[collection]/controllers/[collection].js
'use strict';
const { createCoreController } = require('#strapi/strapi').factories;
module.exports = createCoreController('api::user-profile.user-profile', ({ strapi }) => ({
async me(ctx) {
try {
const user = ctx.state.user;
const datas = await strapi.entityService.findMany("api::user-profile.user-profile", {
filters: {
user: {
id: user.id
}
}
})
return datas;
} catch (err) {
ctx.body = err;
}
}
}));
If you will use all endpoints in collection like (create,update,delete,find,findone). You must override the all endpoints . Example is the below.
'use strict';
const { createCoreController } = require('#strapi/strapi').factories;
module.exports = createCoreController('api::education.education', ({ strapi }) => ({
async create(ctx) {
try {
const user = ctx.state.user;
ctx.request.body.data.users_permissions_user = user.id
const datas = await strapi.entityService.create("api::education.education", {
...ctx.request.body
})
return datas;
} catch (err) {
ctx.body = err;
}
},
async update(ctx) {
try {
const user = ctx.state.user;
ctx.request.body.data.users_permissions_user = user.id
const { id } = ctx.params;
const experienceData = await strapi.entityService.findMany("api::education.education", {
filters: {
users_permissions_user: {
id: user.id
},
id: id
}
});
if (experienceData.length === 0) {
return {
data: null,
error: {
message: ''
}
}
}
const datas = await strapi.entityService.update("api::education.education", id, {
...ctx.request.body
})
return datas;
} catch (err) {
ctx.body = err;
}
},
async delete(ctx) {
try {
const user = ctx.state.user;
const { id } = ctx.params;
const experienceData = await strapi.entityService.findMany("api::education.education", {
filters: {
users_permissions_user: {
id: user.id
},
id: id
}
});
if (experienceData.length === 0) {
return {
data: null,
error: {
message: ''
}
}
}
const datas = await strapi.entityService.delete("api::education.education", id)
return datas;
} catch (err) {
ctx.body = err;
}
},
async findOne(ctx) {
try {
const user = ctx.state.user;
const { id } = ctx.params;
const experienceData = await strapi.entityService.findMany("api::education.education", {
filters: {
users_permissions_user: {
id: user.id
},
id: id
}
});
if (experienceData.length === 0) {
return {
data: null,
error: {
message: ''
}
}
}
const datas = await strapi.entityService.findOne("api::education.education", id)
return datas;
} catch (err) {
ctx.body = err;
}
},
async find(ctx) {
try {
const user = ctx.state.user;
const datas = await strapi.entityService.findMany("api::education.education", {
filters: {
users_permissions_user: {
id: user.id
}
}
})
return datas;
} catch (err) {
ctx.body = err;
}
},
}));
No extra endpoints and no extra codes.
Strapi v4
Yes, creating separate endpoint for this task would be great.
Instead of /api/projects/:user using this type of route, use /api/projects as you can get current logged in users details from ctx.state.user
No, Instead of modifying your existing controller create new controller and use that controller to satisfy your needs.
I ended up extending my controller. In src/api/controllers/project.js I made the following changes:
"use strict";
const { createCoreController } = require("#strapi/strapi").factories;
module.exports = createCoreController("api::project.project", {
async find(ctx) {
const user = ctx.state.user;
ctx.query.filters = {
...(ctx.query.filters || {}),
user: user.id,
};
return super.find(ctx);
},
});
Then simply call the /api/projects endpoint.
Answer based on this guide Limit access of Strapi users to their own entries.

how can I upload image file on server with ionic?

I have searched 'file transfer' and 'firebase storage'. but It didn't run.
const uploadTask = imageRef.put(this.selectedPhoto);
uploadTask.on('state_changed', function(snapshot) {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED:
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING:
console.log('Upload is running');
break;
}
}, function(error) {
console.log('firebase error : ' + error);
}, function() {
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
});
});
The log doesn't appear.
So I don't know what to do and how to do..
Please help me..
Below is the example code. Use FileTransfer plugin.
https://ionicframework.com/docs/native/file-transfer
import { Camera, CameraOptions } from '#ionic-native/camera/ngx';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '#ionic-native/file-transfer/ngx';
import { File } from '#ionic-native/file/ngx';
constructor{
private camera: Camera,
private transfer: FileTransfer,
private file: File,
) {
}
takePhoto(){
const options: CameraOptions = {
quality: 50,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.CAMERA,
correctOrientation: true
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
this.uploadPhoto(imageData); //call your function to upload image
}, (err) => {
// Handle error
});
}
uploadPhoto(path){
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'file',
fileName: '.png',
chunkedMode: false,
//mimeType: "image/jpeg",
}
fileTransfer.upload(path, 'yourUrl.com/imageupload', options)
.then((data) => {
console.log(JSON.parse(data.response));
let res = JSON.parse(data.response);
if (res.status == 1) {
tconsole.log('Image Uploaded successfull');
}
}, (err) => {
console.log(err);
});
}

Update data if exist in firebase

I'm trying to update a data if it exists
var ref = firebase.database().ref().child('users');
var refUserId = firebase.database().ref().child('users').orderByChild('id').equalTo(Auth.$getAuth().uid);
refUserId.once('value', function (snapshot) {
console.log(snapshot);
if (snapshot.exists()) {
snapshot.ref().update(vm.user_infos);
} else {
ref.push({
player: vm.user_infos.player,
id: vm.user_infos.id
}, function(error) {
console.log(error);
})
}
});
Push is working fine, but the update did not.
snapshot.ref is not a function
In the snapshot () log console:
I tried this way too:
if (snapshot.exists()) {
refUserId.update({
player: vm.user_infos.player,
id: vm.user_infos.id
}, function(error) {
console.log(error);
})
Result:
refUserId.update is not a function
User structure
The first problem is that the snapshot's ref property is an object - not a function.
The second is that the snapshot refers to the users path, so you should check for a user that matches your query like this:
var ref = firebase.database().ref().child('users');
var refUserId = ref.orderByChild('id').equalTo(Auth.$getAuth().uid);
refUserId.once('value', function (snapshot) {
if (snapshot.hasChildren()) {
snapshot.forEach(function (child) {
child.ref.update(vm.user_infos);
});
} else {
snapshot.ref.push({
player: vm.user_infos.player,
id: vm.user_infos.id
});
}
});
And if you want to know when the update or push has completed, you could use promises:
refUserId
.once('value')
.then(function (snapshot) {
if (snapshot.hasChildren()) {
return snapshot.forEach(function (child) {
child.ref.update(vm.user_infos);
});
} else {
return snapshot.ref.push({
player: vm.user_infos.player,
id: vm.user_infos.id
});
}
})
.then(function () {
console.log('update/push done');
})
.catch(function (error) {
console.log(error);
});

How can I use Ionic 2 Pulling Refresher in my app?

Hi all I'M working on angularjs 2/ionic2 mobile app , i need to do pulling refresher in my app, we have tried this link:- https://ionicframework.com/docs/v2/api/components/refresher/Refresher/ process i got refreshing the page but it's not get dismissLoader, we have given the images of my app refreshing:-
we don't know where we did the mistake and where we need to add the correct functionality in my project...
while we pulling the page it's refreshing but it's not get dismiss, Refreshing text and icon showing it's not get dismissed...
what we expecting once we pulled the page it's need to refresh after that refreshing text and icon need to be dismiss...
**we added coding only in html:-****
<ion-refresher (ionRefresh)="setFilteredItems($event)">
<ion-refresher-content refreshingSpinner="circles" refreshingText="Refreshing...">
</ion-refresher-content>
</ion-refresher>
we have not added anything in type script part...so please check and update the solution please....
we have created example Plunker
please update the plunker as well to know the solution, thanks.....
My Type Script constructor code:-
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { GlobalStateService } from '../../services/global-state.service';
import { AccountSigninPage } from '../account-signin/account-signin';
import { AccountSignupPage } from '../account-signup/account-signup';
import { ActivityAddPage } from '../activity-add/activity-add';
import { Activity } from "../../services/actopi-sdk/model/Activity";
import { UserLoginService } from "../../services/account-management.service";
import { ResourceListPage } from '../resource-list/resource-list';
import { IamAuthorizerClient } from "../../services/actopi-api.service";
import { CustomAuthorizerClient, NoAuthorizationClient, UserPoolsAuthorizerClient } from "../../services/actopi-api.service";
import { Config } from '../../config/config'
import { Logger } from '../../services/logger.service';
import 'rxjs/add/operator/debounceTime';
import { FormControl } from '#angular/forms';
declare const AWS: any;
#Component({
templateUrl: 'activity-list.html',
})
export class ActivityListPage {
initialized = false;
accountSigninPage = AccountSigninPage;
accountSignupPage = AccountSignupPage;
activityAddPage = ActivityAddPage;
activitys: Activity[] = [];
resourceListPage = ResourceListPage;
searchTerm: string = '';
searchControl: FormControl;
displayDeleteActivityConfirmation(activityId, activityName) {
console.log("Deleting activityID " + activityId);
let confirm = this.globals.getAlertController().create({
title: 'Delete activity?',
message: `Are you sure you want to delete [<b>${activityName}</b>]? All resources and bookings associated with [<b>${activityName}</b>] will also be deleted!`,
buttons: [
{
text: 'Cancel',
handler: () => { /* do nothing */ }
},
{
text: 'OK',
handler: () => {
this.deleteActivity(activityId)
.then(() => {
this.globals.dismissLoader();
this.globals.displayToast(`Activity [${activityName}] has been successfully deleted`);
})
.catch((err) => {
this.globals.dismissLoader();
this.globals.displayAlert('Error encountered',
'Delete failed. Please check the console logs for more information.');
console.log(err);
});
}
}
]
});
confirm.present();
}
deleteActivity(activityId): Promise<void> {
return new Promise<void>((resolve, reject) => {
// delete from the database
this.globals.displayLoader("Deleting...");
this.customAuthClient.getClient().activitysDelete(activityId).subscribe(
() => {
// remove the item from the activitys array
let index = this.activitys.findIndex(activity => { return activity.activityId == activityId });
if (index > -1) {
this.activitys.splice(index, 1);
}
resolve();
},
(err) => {
reject(err);
}
);
});
}
gotoResourceListPage(activity) {
this.navCtrl.push(ResourceListPage, activity);
}
filterItems(searchTerm): void {
this.activitys = [];
this.userPoolsAuthClient.getClient().activitysList().subscribe(
(data) => {
this.activitys = data.items.filter((activity) => {
return activity.name.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1;
});
this.globals.dismissLoader();
this.initialized = true;
},
(err) => {
this.globals.dismissLoader();
this.initialized = true;
console.error(err);
this.globals.displayAlert('Error encountered',
`An error occurred when trying to load the activitys. Please check the console logs for more information.`)
});
}
loadActivitysWithAuth(): void {
this.activitys = [];
this.userPoolsAuthClient.getClient().activitysList().subscribe(
(data) => {
// this.activitys = data.items
// sort by name
let searchTerm: string = '';
// this.activitys = data.items.sort((a, b) => {
// return a.name.localeCompare(b.name);
// });
this.globals.dismissLoader();
this.initialized = true;
},
(err) => {
this.globals.dismissLoader();
this.initialized = true;
console.error(err);
this.globals.displayAlert('Error encountered',
`An error occurred when trying to load the activitys. Please check the console logs for more information.`)
}
);
};
loadActivitysWithoutAuth(): void {
this.activitys = [];
this.noAuthClient.getClient().activitysList().subscribe(
(data) => {
// this.activitys = data.items
// sort by name
this.activitys = data.items.sort((a, b) => {
return a.name.localeCompare(b.name);
});
this.globals.dismissLoader();
this.initialized = true;
},
(err) => {
this.globals.dismissLoader();
this.initialized = true;
console.error(err);
this.globals.displayAlert('Error encountered',
`An error occurred when trying to load the activitys. Please check the console logs for more information.`)
}
);
};
constructor(private navCtrl: NavController, public globals: GlobalStateService, private noAuthClient: NoAuthorizationClient, private customAuthClient: CustomAuthorizerClient, private userPoolsAuthClient: UserPoolsAuthorizerClient, private authClient: IamAuthorizerClient) {
this.searchControl = new FormControl();
}
ionViewDidEnter() {
Logger.banner("Activitys");
this.activitys = [];
if (!this.initialized) {
this.initialized = false;
if (UserLoginService.getAwsAccessKey() != null) {
// if (CognitoUtil.getUserState() === UserState.SignedIn) {
// console.log(AWS.config.credentials);
UserLoginService.getAwsCredentials()
.then((data) => {
this.globals.displayLoader("Loading...");
this.setFilteredItems(refresher);
this.searchControl.valueChanges.debounceTime(700).subscribe(search => {
this.globals.displayLoader("Loading...");
this.setFilteredItems(refresher);
this.globals.dismissLoader();
});
})
.catch((err) => {
console.log("ERROR: Unable to load activitys!");
console.log(err)
})
}
}
}
setFilteredItems(refresher) {
return this.filterItems(this.searchTerm);
refresher.complete();
}
}
You need to call refresher.complete() to dismiss your refresher once loading of new data is done..
setFilteredItems(refresher?:any){
//async call to load.
// in the then function
if(refresher)
refresher.complete();
}
}
The refresher is sent from the html onRefresh. With ? you can call without passing object in your code.
this.setFilteredItems();
Also consider refactoring your code. You should ideally call complete after async task ia done and no point in returning another function to the html side and calling complete after return will just end up as dead code.

Resources