firebase-admin & npm run dev issues - npm

I'm having two problems with my code. First, I can run the front-end part without any problems. I can access the site, there is no problem with that. But when I enter the command "npm run dev" to run the back-end part, I get
PS C:\Users\skrpn\OneDrive\Masaüstü\honeytype\web\backend> npm run dev
> monkeytype-backend#1.14.3 dev
> ts-node-dev ./src/server.ts -- --inspect --transpileOnly
'ts-node-dev' is not recognized as an internal or external command,
operable program or batch file.
My second problem is that I have a problem with firebase-admin defined in server.ts that I don't know what it is. I am posting the error below. I don't know why I got it and what I should do.
import "dotenv/config";
import admin, { ServiceAccount } from "firebase-admin";
// #ts-ignore
import serviceAccount from "./credentials/serviceAccountKey.json"; // eslint-disable-line require-path-exists/exists
import * as db from "./init/db";
import jobs from "./jobs";
import { getLiveConfiguration } from "./init/configuration";
import { initializeDailyLeaderboardsCache } from "./utils/daily-leaderboards";
import app from "./app";
import { Server } from "http";
import { version } from "./version";
import { recordServerVersion } from "./utils/prometheus";
import * as RedisClient from "./init/redis";
import { initJobQueue } from "./tasks/george";
import Logger from "./utils/logger";
async function bootServer(port: number): Promise<Server> {
try {
Logger.info(`Starting server version ${version}`);
Logger.info(`Starting server in ${process.env.MODE} mode`);
Logger.info(`Connecting to database ${process.env.DB_NAME}...`);
await db.connect();
Logger.success("Connected to database");
Logger.info("Initializing Firebase app instance...");
admin.initializeApp({
credential: admin.credential.cert(
serviceAccount as unknown as ServiceAccount
),
});
Logger.success("Firebase app initialized");
Logger.info("Fetching live configuration...");
const liveConfiguration = await getLiveConfiguration();
Logger.success("Live configuration fetched");
Logger.info("Connecting to redis...");
await RedisClient.connect();
if (RedisClient.isConnected()) {
Logger.success("Connected to redis");
Logger.info("Initializing task queues...");
initJobQueue(RedisClient.getConnection());
Logger.success("Task queues initialized");
}
initializeDailyLeaderboardsCache(liveConfiguration.dailyLeaderboards);
Logger.info("Starting cron jobs...");
jobs.forEach((job) => job.start());
Logger.success("Cron jobs started");
recordServerVersion(version);
} catch (error) {
Logger.error("Failed to boot server");
Logger.error(error);
return process.exit(1);
}
return app.listen(PORT, () => {
Logger.success(`API server listening on port ${port}`);
});
}
const PORT = parseInt(process.env.PORT ?? "5005", 10);
bootServer(PORT);
I tried using nodemon to fix the problem with "npm run dev". There was no change. I don't know what the problem is with the firebase-admin part either. I did the whole installation without any problems.
Also, when I start with nodemon, the command prompt enters the loop. I don't know if it will work for the solution, but I wanted to say it.

Related

Test execution is different between Github Actions and local

I'm testing my express.js API via importing the root app instance and using it through chai-http. The tests are run via mocha.
As the title say, when I run my tests via Github Actions the results are different than when they are run locally. On Github Actions, I get an automatic 503 error from express on any of the test requests or any type of request, while locally all tests run fine and pass. When the 503 is received the entire test runner hangs as well and doesn't exit until the MongoDB driver times out with an error.
Initially the test timed out so I added --timeout 15000 to bypass it, hopefully temporarily.
This is the general setup and imports done before the tests
import {server} from "../bld/server.js";
import {join} from "path";
import chai from "chai";
import chaiHttp from "chai-http";
import chaiAjv from "chai-json-schema-ajv";
chai.use(chaiHttp);
chai.use(chaiAjv);
const api = !!process.env.TEST_MANUAL
? (process.env.API_ADDRESS ?? "http://localhost") + ":" + (process.env.API_PORT ?? "8000")
: server;
console.log((typeof api == "string")
? `Using manually hosted server: "${api}"`
: "Using imported server instance");
const request = chai.request;
const expect = chai.expect;
And the first test looks like this
describe("verification flow", () => {
const actionUrl = "/" + join("action", "verify", "0");
var response;
describe("phase 0: getting verification code", () => {
it("should return a verification code", async () => {
const res = await request(api).post(actionUrl);
expect(res).to.have.status(201);
expect(res).to.have.json;
expect(res.body).to.have.property("verificationCode");
response = res.body;
});
// ....
});
// ...
});
There are no errors on imports, no errors on attaching the server to chai, and from what I can log no issues with file pathing either. At this point I'm lost to as what could be causing the issue and don't know where to look for the root of the problem.
More specific information below:
Dependencies: https://pastebin.com/tu3n9FkZ
Github Actions: https://pastebin.com/HEk5adWQ
No artifacts (dependencies, builds) have been cached according to logs
Thank you for your time and let me know if you need any more information

Apollo GraphQL Client does not work on release build in react native

it's been around two weeks that I'm dealing with this problem.
at first, it did not work at all. After spending several days searching for a solution I could fix it by adding these lines of code to my index.js file.
XMLHttpRequest = GLOBAL.originalXMLHttpRequest ?
GLOBAL.originalXMLHttpRequest :
GLOBAL.XMLHttpRequest;
global.Blob = null
After that, it worked fine in the development mode and everything was fine.
But as soon as I released my app I realized it does not work in the release build!
I'm kind of sure it's a problem with fetch API that apollo uses behind the scenes. But I don't know what to do to fix it.
I also tried to run a new project and paste my code on it, but no luck.
this is my apollo client code:
import ApolloClient from 'apollo-client'
import Statics from './statics'
import {HttpLink} from 'apollo-link-http'
import { InMemoryCache } from '#apollo/client';
const customFetch = (uri, options) => {
return fetch(uri, options)
.then(response => {
if (response.status >= 500) { // or handle 400 errors
return Promise.reject(response.status);
}
return response;
});
};
export const client = new ApolloClient({
link: new HttpLink({uri:`${Statics.baseUrl}/graphql`, fetch:customFetch}) ,
cache: new InMemoryCache(),
});
Try using isomorphic-fetch instead of fetch

TestCafe: Failed to complete a request to url

Summary
We have smoke tests that run shortly after deployment on our web application. Sometimes it takes the login page takes a while for its first load.
Error
- Error in Role initializer -
Failed to complete a request to "https://myurl.com/account/login/" within the
timeout period. The problem may be related to local machine's network or firewall settings, server outage, or network problems that make the server inaccessible.
Possible Solutions
I'm hoping that adding a setPageTimeout in my Roles will solve this issue, however, I can't confirm until Tuesday.
Can anyone confirm if setPageTimeout is the way to go? If not, is there a solution available?
Example Solution
import { Role } from 'testcafe';
import { config, pageWait } './config/config';
import { loginPage } from '../pages'
const defaultPageTimeout = 5000;
export const orgAdminRole: Role = Role(config.baseUrl, async t => {
await t
.setPageLoadTimeout(pageWait.extraLongPoll)
.typeText(loginPage.userNameInput, config.orgAdminUser)
.typeText(loginPage.passwordInput, config.orgAdminPass)
.click(loginPage.loginButton)
.setPageLoadTimeout(defaultPageTimeout);
}, { preserveUrl: true });
export const userRole: Role = Role(config.baseUrl, async t => {
await t
.setPageLoadTimeout(pageWait.extraLongPoll)
.typeText(loginPage.userNameInput, config.user)
.typeText(loginPage.passwordInput, config.userPass)
.click(loginPage.loginButton)
.setPageLoadTimeout(defaultPageTimeout);
}, { preserveUrl: true });
UPD: Use the following API to configure your timeouts:
--page-load-timeout-ms
--ajax-request-timeout-ms
--page-request-timeout-ms
Test.timeouts Method
Old answer:
The reason of this issue is the request timeouts. So, using setPageLoadTimeout is not a solution in your test case.
As a workaround, I suggest you change the request timeouts:
import { Selector } from 'testcafe';
// Import DestinationRequest from the testcafe-hammerhead module. Please, specify your own environment path.
import { DestinationRequest } from '../../../../../../node_modules/testcafe-hammerhead/lib/request-pipeline/destination-request';
fixture `Fixture`
.page `https://example.com`;
test('test', async t => {
// Set timeouts
DestinationRequest.XHR_TIMEOUT = 10 * 60 * 1000; // XHR requests timeout
DestinationRequest.TIMEOUT = 10 * 60 * 1000; // other requests timeout
// Actions and assertions
// Restore default timeouts
DestinationRequest.XHR_TIMEOUT = 2 * 60 * 1000;
DestinationRequest.TIMEOUT = 25 * 1000;
});
We will consider the implementation of public options to set the timeouts in the context of the following issue: https://github.com/DevExpress/testcafe/issues/2940.
As an addition to the previous answer I think TestCafe have changed DestinationRequest exporting mode. So I'm using as import * as DestinationRequest ....

React Native project - cannot make API calls with AwsAmplify through custom library

I have a react-native app (without expo) called myapp.
I have a private custom package called myapp-core, where I handle AwsAmplify services (Auth, Storage) - to do login/signOut/etc.
I want to use myapp-core in myapp project, so I added it as a dependency in package.json ("myapp-core": "file:../myapp-core",) and then yarn install.
The problem I’m facing is that when I call myapp-core.authService.login(username, password) from the mobile project, I catch the error:
“ { “line”:177826, “column”: 17, “sourceURL”:
“http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false”
} ”
From my research, that means my custom library cannot make api calls - but I don’t know exactly.
When I use aws-amplify's Auth object directly in my mobile project, it works.
Hopefully relevant code:
/**=============================**/
/** myapp/CoreServices.js **/
import { AmplifyService } from “myapp-core";
export default class CoreServices {
constructor() {
AmplifyService.configure();
const auth = AmplifyService.authService();
auth
.login(“myusername”, “mypassword”)
.then(user => console.warn("success", user))
.catch(error => console.warn("error", error));
}
}
/**=============================**/
/** myapp-core/AmplifySevice.js **/
import Amplify from 'aws-amplify';
import AuthService from '../AuthService/AuthService';
import awsConfigs from '../aws-exports';
class AmplifyService {
static authServiceInstance = null;
static storageServiceInstance = null;
static configure(config = awsConfigs) {
if (config === null || config === undefined) {
throw new Error('AmplifyService must be initialized with Auth and Storage configurations.');
}
Amplify.configure({
Auth: { /*...*/ },
Storage: { /*...*/ }
});
}
static authService() {
if (!this.authServiceInstance) {
this.authServiceInstance = new AuthService();
}
return this.authServiceInstance;
}
static storageService() {
console.warn('storage service');
// initialize storage service
// return storage service
}
}
I managed to solve my project's issue.
Maybe someone will benefit from my solution.
The problem didn't have anything to do with AwsAmplify, but with the way I linked the projects: myapp-core with myapp.
The issue was that in the myapp-core I am using the aws-amplify package that I would normally link to the mobile projects (react-native link) but in my case I assumed (wrongly) that it wouldn't be the case.
The solution was to link whatever packages were needed in the iOS/Android projects to install the proper pods/gradle libraries, like react-native link amazon-cognito-identity-js for authentication.
... and now I am finally happy :))
Links that shed some light:
https://github.com/facebook/create-react-app/issues/1492
https://eshlox.net/2018/11/12/aws-amplify-react-native-typeerror-cannot-read-property-computemodpow-of-undefined/
In case somebody thinks this isn't the solution and I got lucky or something, please comment or post another response.

Unable to include AB Testing for React Native application

I am integrating A/B Testing for my React Native application using Firebase. I have tried two methods - using react-native-ab and react-native-ab-test.
In the first case, I get an error saying "undefined is not an object(evaluating PropTypes.string)"
In the second case, I get an error saying "index.ios.js tries to require 'react-native' but there are several files providing this module. You can delete or fix them."
In both the cases, I get these errors just by importing the dependency in my JS file. By seeing the github pages of both dependencies, I think there is no need to link both the dependencies and they run fine.
Links :
https://github.com/lwansbrough/react-native-ab
https://github.com/landaio/react-native-ab-test
I installed it with this module and it works perfectly, you can try this:
https://github.com/invertase/react-native-firebase
https://rnfirebase.io/docs/v5.x.x/getting-started
and then it is to configure the remote config so that the a-b test works for you
https://rnfirebase.io/docs/v5.x.x/config/reference/config
I'm using A/B testing and works for me with this module:
"react-native-firebase": "3.3.1",
and needs pod too.
pod 'Firebase/Core', '~> 5.11.0'
pod 'Firebase/RemoteConfig', '~> 5.11.0'
My logic
import firebase from 'react-native-firebase';
setRemoteConfigDefaults() {
if (__DEV__) {
firebase.config().enableDeveloperMode();
}
// Set default values
firebase.config().setDefaults({
my_variant_remote_config_param: ''
});
}
/**
* FIREBASE remote config fetch
* #param valueToFetch: remote config key
*/
export const fetchRemoteConfig = async (valueToFetch: RemoteConfigKeysTypes): Promise<string> => {
try {
await firebase.config().fetch();
await firebase.config().activateFetched();
const snapshot = await firebase.config().getValue(valueToFetch);
const response = snapshot.val();
return response;
} catch (error) {
firebase.analytics().logEvent('remote_config_get_value_error', { error, key: valueToFetch });
return null;
}
};
More Info:
https://www.npmjs.com/package/react-native-firebase