How to use config module on main.ts file - nestjs

I have set a config module, according to https://docs.nestjs.com/techniques/configuration then how can I use it on main.ts??
nestjs version: 6.1.1

In your main.ts file after you use the NestFactory method to create the application you can use const configService = app.get<ConfigService>(ConfigService); to get the service from the context. If you want to leave out the generics that works too. After that you use it just like you would anywhere else in your app: configSerivce.get('key');

Related

How to configure Serverless Lambda for Graphql API with Typescript

I am new to AWS and trying to deploy a GraphQL API written in NodeJS as an AWS Lambda using Serverless. I have followed several tutorials that are close to what I am doing but cannot get the handler to work. The closest tutorial to what I am doing was using JavaScript, where I am using TypeScript. I followed closely but using TypeScript. I am getting errors that it cannot find the handler module (Error: Cannot find module 'lambda').
My handler file is named lambda.ts looks like this
`
import {app} from './app';
import {serverless} from 'serverless-http';
export const handler = serverless(app);
`
My serverless.yml looks like this
`
service: graphql-api
frameworkVersion: '3'
provider:
name: aws
runtime: nodejs12.x
region: us-east-1
functions:
serverlessApi:
handler: lambda.handler
app.ts
import express from 'express';
import cors from 'cors';
import { graphqlHTTP } from 'express-graphql';
import { schema, resolvers } from './api-schema/';
import { loginMiddleware } from './login-middleware';
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(loginMiddleware);
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
graphiql: true,
rootValue: resolvers,
})
);
export default app;
`
The lambda.js, app.ts, and serverless.yml files are all in the same root directory.
I have tried to convert the code to JavaScript and get errors that it cannot find the 'app' module. (Cannot find module './app')
lambda.js and looks like this
`
const app = require('./app');
const serverless = require('serverless-http');
module.exports.handler = serverless(app);
`
I have also tried to export 'app' as default or named getting the same result. I am out of ideas. Any help is much appreciated.
The problem likely stems from the fact that you're mixing JS and TS here. I don't see you using TypeScript really in app.ts, so to keep things simple, I would recommend switching to pure js for now to make things work, and then switching to TS.
You're also using ESM, that is not supported in nodejs12.x runtime, and mixing ESM and CommonJS (your lambda.js is using CommonJS) can cause some troubles, so I would suggest to switch the app.js implementation to use requires instead of imports and export in CommonJS style, at least in initial iteration.
You can also safely upgrade to nodejs16.x runtime, as nodejs12.x is going to be deprecated soon.
If you'd like to stick to TypeScript and/or ESModules, you'll need a plugin like https://www.npmjs.com/package/serverless-esbuild and I would recommend to do so, after successfully deploying the initial version.
Still have no solution to the issue after several changes. I did upgrade to Node16, but more importantly, I followed the documentation here:
https://www.prisma.io/docs/guides/deployment/deployment-guides/deploying-to-aws-lambda#deployment-using-serverless-webpack
The npm package serverless-esbuild started me in the right direction, but it had issues with prisma.
I don't like having to use webpack, and I am still getting a CORS error, but the original issue of not finding the module is fixed.
Also changed my handler file to look like this:
import app from './app';
import serverless from 'serverless-http';
const handler = () => {
return serverless(app);
}
export { handler };
I was surprised to see the difference in the webpack build and the esbuild. esbuild is 1.2 MB, where the webpack build is 96 MB! Subsequent runs hit the aws max at around 200MB and failed to upload. It also takes at least 2x as long to complete. I am considering looking at alternatives to serverless as it seems to be tough to configure for what I have to think is a basic graphql implementation.

How to use konva in nestjs

I need konva to run on nodejs. I used this documentation from the creators themselves.
doc - https://github.com/konvajs/konva#4-nodejs-env
I myself use nestjs.
error
package.json
I solved this problem by changing the import
import Konva from 'konva';
on
const Konva = require('konva/cmj').default;

Prevent webpack from removing crypto in nodejs API

I have a node-js API that's part of an nx workspace and I'm trying to use the core crypto node-js module, however I think it's getting stripped out by webpack.
My code uses the following:
crypto.getRandomValues(new Uint32Array(1))[0].toString(16)
However I get a runtime error:
ReferenceError: crypto is not defined
Am I right in thinking this issue is likely being caused by webpack? And if so, how can I use crypto in my API?
I'm very new to webpack, so I'm pretty clueless here. My nx project uses the #nrwl/node:webpack executor (the default for node-js APIs), and I've followed the steps here on how to customize this projects webpack configuration, so my custom webpack config is being used, I just dont know what to do with it on order to allow my API to use crypto.
Any help on this would be appreciated.
For completeness, here's what my custom webpack config looks like, but it makes no difference to the problem. Note that his was crafted based on some of the suggested answers here:
const { merge } = require('webpack-merge');
/** #type { import('webpack').Configuration } */
const webpackConfig = {
target: 'node',
resolve: {
fallback: {
"crypto": false
}
}
};
module.exports = (config, context) => merge(config, webpackConfig);
Edit: As a workaround, I've imported the randomUUID function from crypto and can use this to do what I need to do. It seems having this import means crypto gets included in the webpack.
import { randomUUID } from 'crypto';
randomUUID().split('-')[0];
In your above code + runtime error, it seems like you haven't imported crypto correctly.
Furthermore you are mixing up some concepts. Webpack is normally used for frontend projects, as Node.js supports requiring modules out of the box and you don't need to compile your code, as you don't need to generate a javascript bundle that's servable by browsers.
Because your project runs in the browser, but your tests run in Node, which has a different global namespace, you get issues. In the browser crypto is defined globally, but in Node you need to import the crypto standard library, the "suggested answers" you are linking to talks about this concept.
To fill in the gap between browser and Node, to ensure the code you write works for test + browser, you use polyfills.
In your usecase you have a Node.js project. Crypto is a standard library for Node.js and you can just require it, why should you configure webpack to create fallbacks for it or use polyfills?

Clarification of jest mocking behaviour in nested modules

I'm confused by the jest docs.
This is in the documentation for jest.mock():
Modules that are mocked with jest.mock are mocked only for the file that calls jest.mock. Another file that imports the module will get the original implementation even if it runs after the test file that mocks the module.
But the example in the general section on mocking has:
axios imported in a file called Users
users.test.js sets up the following mock:
import axios from 'axios';
import Users from './users';
jest.mock('axios');
The documentation suggests to me that the test file is should not be able to mock axios in the src users.js file... and yet, this is the example in the docs, so surely it should work.
In my test suite I have a test file that implements a very similar pattern
const fetch = require('node-fetch')
const { getApp } = require('../get-app');
jest.mock('node-fetch', () => require('fetch-mock-jest').sandbox())
the only differences being that
node-fetchis not imported directly within get-app.js, but by one of its dependencies
I use require() rather than import
But my example does not work; when I log out the value of teh fetch function in the dependency that calls it, I get the unmocked implementation of node-fetch.
Can anybody explain
How the example in the jest docs is consistent with the description of how mocking is supposed to work
Why the example in the docs would work, but mine doesn't
Have discovered the issue is with the project being a monorepo, which means there are multiple copies of node-fetch around.
Other than explicitly requiring the other package's copy of node-fetch (i.e. require('../other-package/node_modules/node-fetch'), how could I get the tests of one package to mock a node_module contained in another package's node_modules directory?

Webpack-dev-server and isomorphic react-node application

I've managed to properly use webpack dev server alongside with a node server (express), using the plugin section inside webpack's config.
It all works fine but now I'm trying to go isomorphic and use client-side components inside the express application.
So far the only problem I'm encountering is that without webpack 'parsing' my server-side code I get to a situation where I require components but the paths are not solved
I.E.
Inside a component
'use strict';
import React from 'react';
import { RouteHandler, Link } from 'react-router';
import Header from 'components/header/main'; // <-- This line causes the error because webpack is not working when parsing this JSX server-side
export default React.createClass({
displayName: 'App',
render() {
return ( // ... More code
Shall I configure webpack in another way or do I have to change all the imports to be valid server-side?
the codebase is here in case you want to see the actual state https://github.com/vshjxyz/es6-react-flux-node-quickstart
In order to be able to require components in a way such as require('components/Header.js'); and avoid using long relative paths such as require('../../../../../../Header.js'); you can add this code to your node app before any require() calls:
process.env.NODE_PATH = __dirname;
require('module').Module._initPaths();
However, since this relies on a private Node.js core method, this is
also a hack that might stop working on the previous or next version of
node.
Other possible solutions to this problem can be found at https://gist.github.com/branneman/8048520
I see 2 options:
Compile client code with webpack as well. If client's entry
point is in the same dir as server's - it should work with your
present code. This looks natural to me.
Use relative paths i.e.
import Header from './components/header/main'

Resources