pdfjs throws a TypeError, losing hair - node.js

import React, { Component } from "react";
import pdfjs from "pdfjs-dist";
import pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";
class PdfLoader extends Component {
state = {
pdfDocument: null
};
componentDidMount() {
const { url } = this.props;
pdfjs
.getDocument({ url: url, eventBusDispatchToDOM: true })
.promise.then(pdfDocument => {
this.setState({
pdfDocument: pdfDocument
});
});
}
}
This builds fine under yarn, but at run time, pdfjs.getDocument (ok, minimized, something like co.a.getDocument) throws a TypeError saying it can't handle getDocument of undefined. My other source files and the console show that I am loading my pdf.worker..worker.js file.
I inherited this code from a former co-worker and a previous build on his machine worked, but on mine it always throws this error.

Related

how to prevent file upload when body validation fails in nestjs

I have the multipart form to be validated before file upload in nestjs application. the thing is that I don't want the file to be uploaded if validation of body fails.
here is how I wrote the code for.
// User controller method for create user with upload image
#Post()
#UseInterceptors(FileInterceptor('image'))
create(
#Body() userInput: CreateUserDto,
#UploadedFile(
new ParseFilePipe({
validators: [
// some validator here
]
})
) image: Express.Multer.File,
) {
return this.userService.create({ ...userInput, image: image.path });
}
Tried so many ways to turn around this issue, but didn't reach to any solution
Interceptors run before pipes do, so there's no way to make the saving of the file not happen unless you manage that yourself in your service. However, another option could be a custom exception filter that unlinks the file on error so that you don't have to worry about it post-upload
This is how I created the whole filter
import { isArray } from 'lodash';
import {
ExceptionFilter,
Catch,
ArgumentsHost,
BadRequestException,
} from '#nestjs/common';
import { Request, Response } from 'express';
import * as fs from 'fs';
#Catch(BadRequestException)
export class DeleteFileOnErrorFilter implements ExceptionFilter {
catch(exception: BadRequestException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
const getFiles = (files: Express.Multer.File[] | unknown | undefined) => {
if (!files) return [];
if (isArray(files)) return files;
return Object.values(files);
};
const filePaths = getFiles(request.files);
for (const file of filePaths) {
fs.unlink(file.path, (err) => {
if (err) {
console.error(err);
return err;
}
});
}
response.status(status).json(exception.getResponse());
}
}

Angular app often takes too long when loading a path with a resolver using ssr

I am having some issues serving my app using ssr. It works fine when it loads normally using ng s --o. But when I serve it with npm run dev:ssr and load the path it sometimes takes extremely long to serve while using the resolver below. Enough to timeout when deployed (>60s). I am using node 10.
solution.resolver.ts
import { Injectable } from '#angular/core';
import { AngularFirestore } from '#angular/fire/firestore';
import {
Resolve,
RouterStateSnapshot,
ActivatedRouteSnapshot
} from '#angular/router';
import { from, Observable } from 'rxjs';
import { map, mergeMap, reduce } from 'rxjs/operators';
import { Solution } from './Solution.type';
import { AngularFireStorage } from '#angular/fire/storage';
#Injectable({
providedIn: 'root'
})
export class SolutionResolver implements Resolve<Solution[]> {
constructor(
private firestore: AngularFirestore,
private storage: AngularFireStorage
) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
): Observable<any> { // Solution[]
return this.firestore.collection('solutions').get() // Observable<doc>
.pipe(
map( snapshot => snapshot.docs.map( doc => doc.data() ) as Solution[]), // Observable<Solution[]>
mergeMap( solutions => from(solutions) ), // stream of Observable<Solution>
mergeMap( solution => {
return this.storage.ref( solution.image ).getDownloadURL()
.pipe( map( url => ({...solution, image: url}) ))
}), // stream of <Observable<Solution>
reduce( (acc: Solution[], value ) => {acc.push(value); return acc; }, []) // <Observable<Solution[]>
)
}
}
The issue may be related to this.storage.ref( solution.image ).getDownloadURL(). There are no error messages in the console. To make it even worse sometimes it does work as expected.
I previously had the same issue using the getDownloadURL pipe from angularfire: https://github.com/angular/angularfire/blob/master/docs/storage/storage.md#downloading-files
Any idea what is going wrong?
update: It's probably related to this issue: https://github.com/angular/angularfire/issues/2725

How to test react-native methods?

I want to test Vibration module of react-native, the problem is that I get an error when I try to test it:
With this component:
import React, { useEffect } from 'react';
import { Text, Vibration } from 'react-native';
interface Props {}
export const MyComponent = (props: Props) => {
useEffect(() => Vibration.vibrate(1), []);
return (
<Text>asdaf</Text>
);
};
And this test file:
// #ts-nocheck
import React from 'react';
import { render } from '#testing-library/react-native';
import { NativeModules } from 'react-native';
import { MyComponent } from '../../../src/modules/MyComponent';
describe('MyComponent', () => {
it('alpha', () => {
const { debug } = render(<MyComponent/>);
expect(true).toBeTruthy();
});
});
I get this error:
Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'Vibration' could not be found. Verify that a module by this name is registered in the native binary.
I tried to mock react-native like this:
// #ts-nocheck
import React from 'react';
import { render } from '#testing-library/react-native';
import { NativeModules } from 'react-native';
import { ChatRoomContainer } from '../../../src/modules/ChatRoom';
// Mock NativeModules
jest.mock('react-native', () => ({
...jest.requireActual('react-native'),
Vibration: {
vibrate: jest.fn()
},
__esModule: true
}));
describe('MyComponent', () => {
it('alpha', () => {
const { debug } = render(<ChatRoomContainer/>);
expect(true).toBeTruthy();
});
});
But then I get a ton of warnings related to old modules that should no longer be used:
Warning: CheckBox has been extracted from react-native core and will be removed in a future release. It can now be installed and imported from '#react-native-community/checkbox' instead of 'react-native'. See https://github.com/react-native-community/react-native-checkbox
Warning: DatePickerIOS has been merged with DatePickerAndroid and will be removed in a future release. It can now be installed and imported from '#react-native-community/datetimepicker' instead of 'react-native'. See https://github.com/react-native-community/datetimepicker
What is the best way to test such functionality (like Vibration) of react-native then?
Thanks in advance for you time!
You can mock react-native using the library path, like this:
const mockedVibrate = jest.fn();
jest.mock('react-native/Libraries/Vibration/Vibration', () => ({
vibrate: mockedVibrate,
}));

Issue getting events from Eventbrite API

I'm building a school project using angular js and node js as a backend, I'm trying to display the event in my front-end using Angular JS from EventBrite, After spending a few hours checking different tutorial I wrote this code
Node JS code:
router.get('/', (req, res)=>{
axios.get(`${EventsBriteAPI}`).then(result=>{
let relevantData = result.data.data.events
res.status(200).json(relevantData);
console.log(results );
})
.catch(error => {
res.status(500).send(error);
})
});
My service code:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class EventsService {
uri = 'http://localhost:4600/events';
constructor(private httpClient: HttpClient) {}
getAllEvents(){
return this.httpClient.get(this.uri);
}
}
My component code
import { Component } from '#angular/core';
import { EventsService } from './events.service';
import { Observable } from 'rxjs/internal/Observable';
#Component({
selector: 'events',
templateUrl: 'events.Component.html'
})
export class EventsComponent {
title = "List of events";
eventObservable : Observable<any[]> ;
constructor(service: EventsService){
this.eventObservable = service.getAllEvents();
console.log(this.eventObservable);
}
}
When I'm running my code I'm getting this error
src/app/component/events/events.component.ts(21,5): error TS2322: Type 'Observable' is not assignable to type 'Observable'.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
Type 'Object' is missing the following properties from type 'any[]': length, pop, push, concat, and 26 more. and It's not displaying anything in my front-end
Could you please help me with that.
we don't need to use Observable type variable unless you are using async pipe or for any specific requirement.
You can do some like below,
EventsComponent.ts
eventObservable: any = [];
constructor(private service: EventsService) {
this.service.getAllEvents().subscribe((response: any) =>{
this.eventObservable = response;
console.log(this.eventObservable);
});
}
we generally use ngOnInit() for calling an api data not in the constructor().

Strange behavior with module.exports and async in React

Here's a very strange issue that has me puzzled. After creating a React app with create-react-app, I added these two files:
TestMod.js
const TestMod = {
doSomething() {
}
};
module.exports = TestMod;
Test.js
import React, { Component } from 'react';
import TestMod from './TestMod';
export default class Test extends Component {
render() {
TestMod.doSomething();
return <div>Testing</div>;
}
}
I included the Test component inside App, run npm start, and everything worked fine. Then I changed doSomething to be async, like this
TestMod.js
const TestMod = {
async doSomething() {
}
};
module.exports = TestMod;
Now I get a compilation error:
[1] ./src/Test.js
[1] 26:6-13 "export 'default' (imported as 'TestMod') was not found in './TestMod'
Why? I know how to make it work again:
TestMod.js
export const TestMod = {
async doSomething() {
}
};
Test.js
import React, { Component } from 'react';
import {TestMod} from './TestMod';
export default class Test extends Component {
render() {
TestMod.doSomething();
return <div>Testing</div>;
}
}
But what I'd like to understand is why making a function async causes module.exports to break on the React side. (By the way, it still works fine on the Node.js side).
Thanks,
Alvaro

Resources