RxJS Http Server with typescript compile errors - node.js

I'm pretty newbie with rxjs, can you please tell what's wrong with below?
interface IHTTP {
req: IncomingMessage;
res: ServerResponse;
handler?: Promise<any>;
}
server = http.createServer();
let request$: Observable<any>;
request$ = fromEvent(server, 'request').pipe(
map(([req, res]: [IncomingMessage, ServerResponse]): IHTTP => {
return { req, res } as IHTTP;
}
)
);
Compile error:
TS2345: Argument of type 'OperatorFunction<[IncomingMessage, ServerResponse], IHTTP>' is not assignable to parameter of type 'OperatorFunction<unknown, IHTTP>'.   Type 'unknown' is not assignable to type '[IncomingMessage, ServerResponse]'.

I found the problem I had to define fromEvent's first argument as:
server as FromEventTarget<[http.IncomingMessage, http.ServerResponse]>
Otherwise Typescript thinks it's FromEventTarget<unknown>

Related

How to sign requests using opensearch-js?

I need to sign requests to Opensearch. I'm attempting to use opensearch-js and aws-es-connection to do that.
import {
createAWSConnection,
awsGetCredentials,
} from '#acuris/aws-es-connection';
import { Client } from "#opensearch-project/opensearch";
import { esConfig } from "./config";
export const getClient = async () => {
const awsCredentials = await awsGetCredentials();
const AWSConnection = createAWSConnection(awsCredentials);
const client = new Client({
...AWSConnection,
node: esConfig.uri
});
return client;
};
However, this code complains about the types not being compatible with the destructure ... syntax.
S2345: Argument of type '{ node: string; nodes?: string | string[] | NodeOptions | NodeOptions[]; Connection?: typeof Connection; ConnectionPool?: typeof ConnectionPool; ... 26 more ...; caFingerprint?: string; }' is not assignable to parameter of type 'ClientOptions'.   Types of property 'ConnectionPool' are incompatible.     Type 'typeof import("/packages/api/node_modules/#elastic/elasticsearch/lib/pool/index").ConnectionPool' is not assignable to type 'typeof import("/packages/api/node_modules/#opensearch-project/opensearch/lib/pool/index").ConnectionPool'.       Types of parameters 'opts' and 'opts' are incompatible.
...
Perhaps I'm making a dumb mistake with the destructuring? Is there another way of signing requests for opensearch-js?

Firebase CLI Typescript error TS2345 thrown on code that previously compiled

Good evening,
I recently updated the firebase CLI for cloud functions, and when I try to deploy my old index.ts file, I get a TS2345 error:
src/index.ts:364:13 - error TS2345: Argument of type '(req: Request, res: Response<any>) => Response<any> | Promise<void | Response<any>>' is not assignable to parameter of type '(req: Request, resp: Response<any>) => void | Promise<void>'.
Type 'Response<any> | Promise<void | Response<any>>' is not assignable to type 'void | Promise<void>'.
Type 'Response<any>' is not assignable to type 'void | Promise<void>'.
Type 'Response<any>' is not assignable to type 'Promise<void>'.
364 .onRequest((req, res) => {
my function that is trowing this error looks like this:
exports.https_rec = functions.https
.onRequest((req, res) => {
if (req.method === 'PUT') {
console.log("HTTPS Attempted Connection");
return res.status(403).send('Forbidden!');
}
else{
//Do Stuff
return res.status(200).send("ok");
}
});
Everything was working and uploading fine, but after I updated the CLI, I now get this TS2345 error on code that previously compiled. I found a sample function from Firebase (from a few years ago) where the structure is the same as how I have presented it, which tells me something must have changed recently.
https://github.com/firebase/functions-samples/blob/master/quickstarts/time-server/functions/index.js#L39
Other specs:
Windows 10
NPM Version 14.5.0
Firebase-tools version 8.6.0
Any thoughts or recommendations? Is there an easy code change to make, or should I revert back to an older version of the CLI or tslint?
Thank you for your time in advance!
They changed the return type of https triggers recently.
You shouldn't "return" anything as a response.
Just delete return and you're good to go.
Example:
exports.https_rec = functions.https
.onRequest((req, res) => {
if (req.method === 'PUT') {
console.log("HTTPS Attempted Connection");
return res.status(403).send('Forbidden!');
}
else{
//Do Stuff
res.status(200).send("ok");
}
});

TypeScript - Type undefined is not assignable to type ICustomType

I'm quite new to TypeScript and trying to understand what is the best way to approach such situation in my code.
I have array of objects that have a custom type in my system and I use Array.find method to get one of them. However I receive a compile error saying Type 'undefined' is not assignable to type IConfig.
Here's the code example -
const config: IConfig = CONFIGS.find(({ code }) => code === 'default');
// Type 'undefined' is not assignable to type IConfig
I tried to add undefined as possible type but then I get error on the next line which uses this object Object is possibly 'undefined', e.g. -
const config: IConfig | undefined = CONFIGS.find(({ code }) => code === 'default');
// Object is possibly 'undefined'
if (config.foo) {
return 'bar';
}
What is the best way to approach such type issues?
.find will return undefined if nothing in the array passes the callback test. If you're sure that default code exists in the array, then use the non-null assertion operator:
const config: IConfig = CONFIGS.find(({ code }) => code === 'default')!;
// ^
(If you weren't sure if it exists in the array, the warning you see is there to prompt you to explicitly test for if the item exists before trying to access a property on it, otherwise you'll sometimes get a runtime error:
const config: IConfig = CONFIGS.find(({ code }) => code === 'default');
if (!config) {
return 'No match found';
}
if (config.foo) {
return 'bar';
}
)

Typescript error TS2345 Error: TS2345:Argument of type 'Buffer' is not assignable to parameter of type 'string'

new to Typescript. I am reading some data from RabbitMQ channel and am converting it to JSON object. In this line I get the error
let communicationInformation = JSON.parse(newCommunication.content);
TS2345:Argument of type 'Buffer' is not assignable to parameter of type 'string'.
Do I need to cast the data? I am using Typescript 2.4.1
Amqplib.connect(amqpLibUrl, (err, connection) => {
if (!err) {
connection.createChannel((err, channel) => {
channel.consume('QueueName', newCommunication => {
if (newCommunication != null) {
let communicationInformation = JSON.parse(newCommunication.content);
// Code
}
})
})
}
});
I think the error is thrown on the input parameter of JSON.parse. Try to first call toString on it then pass to the function.
let communicationInformation = JSON.parse(newCommunication.content.toString());
I am not sure what is newCommunication.content. In my case it is a file and I had to specify encoding for fs.readFileSync:
const level = JSON.parse(fs.readFileSync('./path/to/file.json', 'utf-8'));
Next Error was error TS2531: Object is possibly 'null'.
You have to disable strictNullChecks in your compiler

TS2345: Argument of type X is not assignable to parameter of type Y

Weird error with TypeScript:
As the image indicates, the error is:
TS2345: Argument of type 'ErrnoException' is not assignable to
parameter of type '(err: ErrnoException) => void'. Type
'ErrnoException' provides no match for the signature '(err:
ErrnoException): void'.
Here is the code that causes the error:
export const bump = function(cb: ErrnoException){
const {pkg, pkgPath} = syncSetup();
fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2), cb);
};
Anybody know what's going on here?
You are sending a value with the type ErrnoException, while the function you are calling expects a function that takes a parameter of type *ErrnoException** and returns void.
You send:
let x = new ErrnoException;
While the function you call expects
let cb = function(e: ErrnoException) {};
You can change your function to receive the correct parameter like this.
export const bump = function(cb: (err: ErrnoException) => void){
const {pkg, pkgPath} = syncSetup();
fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2), cb);
};

Resources