Error while creating elasticsearch firebase firestore cloud function - android

I am trying to create a cloud function which will be responsible of sending every new entry into the database to the elasticsearch server.
This is what my index.js looks like
const functions = require('firebase-functions');
const request = require('request-promise');
exports.indexUsersToElastic = functions.firestore
.document('users/{id}')
.onWrite(event => {
let userData = event.data.val();
let user_id = event.params.user_id;
console.log('Indexing user:' userData);
let elasticSearchConfig = functions.config().elasticsearch;
let elasticSearchUrl = elasticSearchConfig.url + 'users/user/' + id;
let elasticSearchMethod = postData ? 'POST' : 'DELETE';
let elasticSearchRequest = {
method: elasticSearchMethod,
url: elasticSearchUrl,
auth: {
username: elasticSearchConfig.username,
password: elasticSearchConfig.password,
},
body: userData,
json: true
};
return request(elasticSearchRequest).then(response => {
console.log("ElasticSearch response", response);
});
});
And this is what my package.json looks like
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint --ext ./index.js",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "16"
},
"main": "index.js",
"dependencies": {
"firebase-admin": "^10.0.2",
"firebase-functions": "^3.18.0"
},
"devDependencies": {
"eslint": "^8.19.0",
"firebase-functions-test": "^0.2.0",
"tslint": "^6.1.3"
},
"private": true
}
On running firebase deploy --only functions
I get this
Running command: npm --prefix "$RESOURCE_DIR" run lint
> lint
> eslint --ext ./index.js
✔ functions: Finished running predeploy script.
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
✔ functions: required API cloudfunctions.googleapis.com is enabled
✔ functions: required API cloudbuild.googleapis.com is enabled
i functions: preparing codebase default for deployment
Error: Failed to load function definition from source: Failed to generate manifest from function source: SyntaxError: missing ) after argument list
Can anyone navigate me through the problem and its solution?

Related

DetoxRuntimeError: Detox can't seem to connect to the test app(s)! - Android only

I use Detox automation tool for bare React Native project. Everything works perfectly on iOS, but when I run tests on Android I get following errors:
DetoxRuntimeError: Detox can't seem to connect to the test app(s)!
HINT: Have you forgotten to call 'device.launchApp()' in the beginning of your test?
Refer to our troubleshooting guide, for full details: https://wix.github.io/Detox/docs/troubleshooting/running-tests#tests-execution-hangs
and
DetoxRuntimeError: The pending request #9 ("invoke") has been rejected due to the following error: The app has unexpectedly disconnected from Detox server.
Some tests have green status. Tests are run in parallel on multiple emulators.
Below is my configuration for detox:
/detoxrc.json
{
"testRunner": "jest",
"runnerConfig": "e2e/config.js",
"skipLegacyWorkersInjection": true,
"apps": {
"ios": {
"type": "ios.app",
"binaryPath": "ios/build/Build/Products/Debug-iphonesimulator/ProjectName.app",
"build": "RN_SRC_EXT=e2e.js xcodebuild -workspace ios/ProjectName.xcworkspace -scheme ProjectName -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build -UseModernBuildSystem=YES -destination 'platform=iOS Simulator,name=iPhone 11'"
},
"android": {
"type": "android.apk",
"binaryPath": "android/app/build/outputs/apk/release/app-release.apk",
"testBinaryPath": "android/app/build/outputs/apk/androidTest/release/app-release-androidTest.apk",
"build": "cd android && RN_SRC_EXT=e2e.js ./gradlew clean assembleRelease assembleAndroidTest -DtestBuildType=release && cd .."
}
},
"devices": {
"simulator": {
"type": "ios.simulator",
"device": {
"type": "iPhone 11"
}
},
"emulator": {
"type": "android.emulator",
"device": {
"avdName": "Pixel_XL"
}
}
},
"configurations": {
"ios": {
"device": "simulator",
"app": "ios"
},
"android": {
"device": "emulator",
"app": "android"
}
}
}
/e2e/config.js
module.exports = {
preset: 'react-native',
setupFilesAfterEnv: ["./init.js"],
setupFiles: [
"<rootDir>/../node_modules/react-native/jest/setup.js",
],
testPathIgnorePatterns: ["/node_modules/"],
testMatch: [
"<rootDir>/*.e2e.js"
],
transformIgnorePatterns: [
'node_modules/(?!(jest-)?#react-native|react-native|#react-native-community|#react-navigation)'
],
};
/e2e/init.js - File which is run after environment setup
import detox from 'detox';
import packageFile from '../package.json';
const detoxConfig = packageFile.detox;
jest.setTimeout(120000);
beforeAll(async () => {
await detox.init(detoxConfig, { launchApp: false });
await device.launchApp();
});
afterAll(async () => {
await detox.cleanup();
});
beforeEach(async () => {
await device.reloadReactNative();
});
and test files looks like similar to this one:
describe('some-screen-description', () => {
beforeEach(async () => {
await logInPage.tapLogInButton();
});
it('description', async () => {
await nextScreen.performAction();
});
});
/package.json
"detox": {
"test-runner": "jest",
"runner-config": "e2e/config.js"
}
I use following version of detox: "detox": "^19.6.9".
I use Macbook Pro with M1 processor. Any hints recommended.
Can anyone confirm that it can be problem with installing both APK and test APK ? I don't know how check that both are installed.
in your init.js inside your beforeAll hook, what's the first line doing? Did you try removing that line?
Regarding your apks being installed, if they weren't installed properly, you'd get a different error message(something like the apks couldn't be found, did you run detox build beofre it?). And also looking at your config file + detox build command I'm sure that the apks were built and they're in the right place. To double check you can go to your android's build output directory(see the paths mentioned in binaryPath and testBinaryPath inside your detox config)

Receiving Proxy error: Error occurred while proxying request [ECONNREFUSED] in react app

I have a react application that is making API calls through axios to my backend and I am receiving the error
[HPM] Error occurred while proxying request matt.hearthdisplay.com:3000/api/user/my to http://localhost:8000/ [ECONNREFUSED] (https://nodejs.org/api/errors.html#errors_common_system_errors)
I am not even calling proxy in my package.json so I am not sure why it's even attempting this? For context the API GET requests are working on my coworker's machines with the same code and I have recently moved to a new location with a different wifi router so I am not sure if this is a computer-specific problem.
matt.hearthdisplay.com:3000/api/user/my is my front end react app and http://localhost:8000/ is for my backend.
What could be causing this? I am on a Macbook M1 running Mac OS Montery 12.3 below are my files that should help. I have tried everything online I have found...
API Request thats producing the error
useEffect(() => {
async function inner() {
const response = await axiosClient.get(`/user/my`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.status === 200) {
setFormState({
firstName: response.data.user.first_name,
lastName: response.data.user.last_name,
});
}
}
if (!!token) {
inner();
}
}, [token]);
axiosCLient.ts
import axios, { AxiosResponse } from "axios";
import { apiRoot } from "./variables";
const axiosClient = axios.create({
baseURL: apiRoot,
});
// Timeout in 3 seconds by default
axiosClient.defaults.timeout = 3000;
function handle2xxResponse(response: AxiosResponse<any>): AxiosResponse<any> {
return response;
}
axiosClient.interceptors.response.use(handle2xxResponse);
export default axiosClient;
package.json
{
"name": "webapp",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.7.1",
"#emotion/styled": "^11.6.0",
"#fortawesome/fontawesome-svg-core": "^1.2.36",
"#fortawesome/free-solid-svg-icons": "^5.15.4",
"#fortawesome/react-fontawesome": "^0.1.16",
"#fullhuman/postcss-purgecss": "^4.1.3",
"#mui/icons-material": "^5.2.4",
"#mui/material": "^5.2.4",
"#mui/styled-engine-sc": "^5.1.0",
"#sentry/react": "^6.16.1",
"#sentry/tracing": "^6.16.1",
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"#types/jest": "^26.0.15",
"#types/node": "^12.0.0",
"#types/react": "^17.0.0",
"#types/react-dom": "^17.0.0",
"#types/react-lottie": "^1.2.6",
"axios": "^0.24.0",
"http-proxy-middleware": "^2.0.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-hook-form": "^7.21.2",
"react-lottie": "^1.2.3",
"react-native-dropdown": "^0.0.6",
"react-router-dom": "^6.0.2",
"react-scripts": "4.0.3",
"styled-components": "^5.3.3",
"tailwindcss": "^2.2.19",
"typescript": "^4.1.2",
"web-vitals": "^1.0.1",
"zustand": "^3.6.5"
},
"scripts": {
"build:tailwind": "postcss src/styles/index.tailwind.css -o src/styles/index.css",
"watch:tailwind": "postcss -w src/styles/index.tailwind.css -o src/styles/index.css",
"start": "run-p watch:tailwind start:react",
"start:react": "react-scripts start",
"prebuild": "npm run build:tailwind",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"autoprefixer": "^10.4.0",
"npm-run-all": "^4.1.5",
"postcss": "^8.4.4",
"postcss-cli": "^9.0.2"
}
}
setUpProxy.js
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
createProxyMiddleware("/api", {
target: "http://localhost:8000",
changeOrigin: true,
secure: false,
})
);
};
Trying add the following header in the proxy code;
target: "http://localhost:8000",
headers: {
"Connection": "keep-alive"
},
...
The Keep-Alive general header allows the sender to hint about how the connection may be used to set a timeout and a maximum amount of requests.

Android white screen when running ionic capacitor run with SSL

I'm trying to run a simple test, trying to add ionic and capacitor to an already existing angular project. I have managed to make it work and run correctly but when I add the SSL command to the CLI so that the server runs with HTTPS the app no longer loads and everything I can just see is a blank screen. Moreover if I access the URL manually from the browser everything loads correctly. Could it be there's something wrongly configured in Android Studio or the ionic/capacitor files? I have tried different configurations and different emulated devices w/ different Android versions but there's no use, I haven't been able to make it work. I would certainly appreciate if someone could help me with this...
Running ionic capacitor run android --livereload --external
https://i.stack.imgur.com/ljfUT.png
https://i.stack.imgur.com/8LxNV.png
When I add the --ssl flag to the CLI ionic capacitor run android --livereload --external --ssl
https://i.stack.imgur.com/fS0jV.png
https://i.stack.imgur.com/D3sLL.png
https://i.stack.imgur.com/3v5Bx.png
Capacitor.config
import { CapacitorConfig } from '#capacitor/cli';
const config: CapacitorConfig = {
appId: 'io.ionic.starter',
appName: 'iotest',
webDir: './android/www',
bundledWebRuntime: false
};
export default config;
Angular.json
{
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"cli": {
"defaultCollection": "#ionic/angular-toolkit"
},
"schematics": {
"#ionic/angular-toolkit:component": {
"styleext": "scss"
},
"#ionic/angular-toolkit:page": {
"styleext": "scss"
}
},
"projects": {
"iotest": {
"projectType": "application",
"schematics": {
"#schematics/angular:component": {
"style": "scss"
},
"#schematics/angular:application": {
"strict": true
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {
"outputPath": "./android/www",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets",
{
"glob": "**/*.svg",
"input": "./node_modules/ionicicons/dist/ionicicons/svg",
"output": "./svg"
}
],
"styles": [
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "iotest:build:production"
},
"development": {
"browserTarget": "iotest:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "#angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "iotest:build"
}
},
"test": {
"builder": "#angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
}
}
}
}
},
"defaultProject": "iotest"
}
Ionic.config
{
"defaultProject": "iotest",
"projects": {
"iotest": {
"name": "iotest",
"integrations": {
"capacitor": {}
},
"type": "angular"
}
}
}
Angular
Angular CLI: 12.1.4
Node: 16.14.0 (Unsupported)
Package Manager: npm 8.3.1
OS: win32 x64
Angular: 12.1.5
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router
Package Version
---------------------------------------------------------
#angular-devkit/architect 0.1201.4
#angular-devkit/build-angular 12.1.4
#angular-devkit/core 12.1.4
#angular-devkit/schematics 12.1.4
#angular/cli 12.1.4
#schematics/angular 12.1.4
rxjs 6.6.7
typescript 4.3.5
Warning: The current version of Node (16.14.0) is not supported by Angular.
NPM
Version 8.3.1
My goal is to make it run with SSL since in a future I will need to apply this to an app that needs to be run with HTTPS
From capacitor.config.ts make change like this:
{
...
server: {
url: 'https://your-local-ip:8100' // like: 192.168.1.66:8100
androidScheme: 'https',
clearText: true // just for test
}
...
}
then open two terminal and run
this command's:
ionic cap run android -l --external --ssl
from second terminal run:
ionic serve 0.0.0.0 --ssl
after all if you still see blank page, open a browser from mobile device and go to https://your-host-ip:8100, then make sure the url is trusted.

How to use Watermarkjs library with ionic capacitor?

Problem
Hi, I recently migrated an ionic cordova project to ionic capacitor following this guide.
I got everything working except for the Watermarkjs library, which I use to watermark pictures taken with the camera of an Android device.
The library used to work fine before the migration, but now everytime I use the functions defined in that library I get this log in Logcat:
Capacitor: Handling local request: http://localhost/9j/4AAQSkZJRgABAQAAAQABAAD
It seems the function is not being called properly.
Code
async takePicture(fieldId){
const image = await Camera.getPhoto({
quality:20,
allowEditing:false,
resultType: CameraResultType.Base64,
source: CameraSource.Prompt
});
let finalImage = await this.addTextWatermark(image.base64String); //problem begins here
console.log("Image with watermark, " finalImage); // this is never printed out in logcat
}
// Function that adds a watermark
// reference: http://brianium.github.io/watermarkjs/text.html
addTextWatermark(base64String){
let result = await watermark([base64String])
.dataUrl(watermark.text.lowerLeft( 'Watermark text', '48px Josefin Slab', '#ffffff', 0.9) )
.then( image => {
return image;
}).catch(error => {
return "error";
})
return result;
}
What I've tried...
Adding watermarkjs script in angular.json scripts section and running npx cap copy, as suggested in this StackOverflow question
angular.json (excerpt)
{
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
"version": 1,
"defaultProject": "app",
"newProjectRoot": "projects",
"projects": {
"app": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {},
"architect": {
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {
"outputPath": "www",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"assets": [
{
"glob": "**/*",
"input": "src/assets",
"output": "assets"
},
{
"glob": "**/*.svg",
"input": "node_modules/ionicons/dist/ionicons/svg",
"output": "./svg"
}
],
"styles": [
{
"input": "src/theme/variables.scss"
},
{
"input": "src/global.scss"
}
],
"scripts": [
"./node_modules/watermarkjs/dist/watermark.js" <----- Added script here
]
} ...
Using different input types for the watermark() function. (file, blob, etc.)
I think the problem is related to not importing the functions properly.
If the library is incompatible with ionic capacitor...
Does anyone know a workaround for this problem?

React Native & Socket.io - cannot establish connection between app and server

I am building a chat app for android using React Native & Socket.io.
The issue is that I can't establish a connection between the app and the server. It gives me a connection error saying Websocket Error.
I tried changing the App Socket Io URI to localhost: port (this gives transport error or timeout error), ip: port (this gives Websocket error), set diff options. Then tried using require syntaxes instead of import for the server. Then installed older versions React-native and socket.io & socket.io-client, still no luck! Then found an app repo from github, installed it, and tried running the app. same error. Also changed cleartextTrafficPermitted="true" in Android manifest file.
Node: v12.13.0
Testing on external devices:
Moto E3(1s gen) -Android 6 Marshmallow.
Redmi Note 7 Pro -Android 9 Pie
screenshot
SERVER:
import express, { Application } from 'express';
import { createServer } from 'http';
import { listen, Server } from 'socket.io';
// set port number
const port = 7777;
// set express
const app: Application = express();
// set express server
const server = createServer(app);
// listen express server updates on socket.io
const io: Server = listen(server, {
transports: ['websocket'],
serveClient: false,
});
io.on('connection', (socket) => {
console.log('connection is made');
socket.emit('commEvent', { data: 'connectionSuccessful' });
socket.on('disconnect', () => {
console.log('connection disconnected');
});
socket.on('new-message', (data) => {
console.log(data.message);
});
});
// listen server updates on specified port
server.listen(port, () => {
console.log('Message app server listening on port:', port);
});
SERVER: package.json
{
"name": "message_app",
"version": "1.0.0",
"description": "Message app server.",
"main": "index.js",
"scripts": {
"start": "node build/index.js",
"watch": "nodemon src/index.ts",
"test": "none",
"build": "npm run lint && tsc-p",
"lint": "eslint --fix --ext .ts ."
},
"dependencies": {
"express": "^4.17.1",
"socket.io": "^2.3.0"
},
"devDependencies": {
"#types/express": "^4.17.6",
"#types/socket.io": "^2.1.8",
"#typescript-eslint/eslint-plugin": "^3.3.0",
"#typescript-eslint/parser": "^3.3.0",
"eslint": "^7.2.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.4",
"nodemon": "^2.0.4",
"prettier": "^2.0.5",
"ts-node": "^8.10.2",
"typescript": "^3.9.5"
}
}
APP:
import React, {useEffect} from 'react';
import {AppScreenStackNavProps} from '../../../Routes/App/AppRouteTypes';
import {View} from 'react-native';
import HomeRoutes from '../../../Routes/Home/HomeRoute';
import io from 'socket.io-client';
export const socket = io('http://192.168.1.38:7777', {
transports: ['websocket'],
jsonp: false,
});
socket.on('commEvent', (data: {data: string}) => {
console.warn(data.data);
});
const HomeScreen = ({navigation}: AppScreenStackNavProps<'Home'>) => {
navigation.setOptions({
headerShown: false,
});
useEffect(() => {
socket.connect();
socket.on('connect', (con: any) => {
console.debug('SOCKET: connected to socket server', con);
});
socket.on('error', (err: any) => {
console.debug('SOCKET: errors ', err);
});
socket.on('connect_error', (err: any) => {
console.debug('SOCKET: connect_error ---> ', err);
});
}, []);
return (
<>
<View style={{flex: 1}}>
<HomeRoutes />
</View>
</>
);
};
export default HomeScreen;
APP: package.json
{
"name": "message_app",
"version": "1.0.0",
"description": "Message app server.",
"main": "index.js",
"scripts": {
"start": "node build/index.js",
"watch": "nodemon src/index.ts",
"test": "none",
"build": "npm run lint && tsc-p",
"lint": "eslint --fix --ext .ts ."
},
"dependencies": {
"express": "^4.17.1",
"socket.io": "^2.3.0"
},
"devDependencies": {
"#types/express": "^4.17.6",
"#types/socket.io": "^2.1.8",
"#typescript-eslint/eslint-plugin": "^3.3.0",
"#typescript-eslint/parser": "^3.3.0",
"eslint": "^7.2.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.4",
"https-localhost": "^4.6.0",
"nodemon": "^2.0.4",
"prettier": "^2.0.5",
"ts-node": "^8.10.2",
"typescript": "^3.9.5"
}
}
I spend a day on this issue what i find is the problem is with your module you installed.
That means if you use typescript in your project make sure to add .d.ts file also for the "socket.io.client" module.
or use this same code in javascript.

Categories

Resources