Please forgive my dumbness, I am new to the concept and stackoverflow community. I have been following tutorial from freeCodeCamp's NestJs Course for Beginner.
https://www.youtube.com/watch?v=GHTA143_b-s&t=21s
And I have been try to use serverless framework to deploy. Whenever I request to endpoints, I I get the error of
Import Module Error: Prisma Cannot find module './prisma/client/index'.
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
My prisma code is : https://github.com/Jaethem8y/research-nestjs/tree/main/prisma
import { Injectable } from '#nestjs/common';
import { ConfigService } from '#nestjs/config';
import { PrismaClient } from '#prisma/client';
#Injectable()
export class PrismaService extends PrismaClient {
constructor(config: ConfigService) {
super({
datasources: {
db: {
url: config.get('DATABASE_URL'),
},
},
});
}
}
Prisma Service code is: https://github.com/Jaethem8y/research-nestjs/tree/main/src/prisma
and serverless.yml : https://github.com/Jaethem8y/research-nestjs/blob/main/serverless.yml
service: research-serverless
frameworkVersion: '3'
plugins:
- serverless-jetpack
provider:
name: aws
runtime: nodejs16.x
region: us-east-2
functions:
api:
handler: dist/lambda.handler
events:
- http:
method: any
path: /{proxy+}
I run npm build then sls deploy. I have no idea what is current issue, and failed to find answer in google due to lack of my skills. Please help me find the solution. Thank you for your time.
I have been tried to google the similar issues, but I could not find one. Seems like the typeorm version of the app is running fine. I am wondering what could cause this issue.
Firstly, you should verify whether or not your repository is actually public before posting links to them. I think your repo is set to private.
Secondly, the error you described comes from the fact that the prisma client does not exist. Please make sure you use prisma generate command to actually generate the client after declaring your models in prisma.schema. You should also verify whether or not you are generating the client in your container image (if this applies).
Related
We are using nestjs for lambda which connects with mongodb for data. We are using nestjs mongoose module. However on deployment for each invocation a new set of connection are made and the previous ones are not released.
We are using forRootAsync
MongooseModule.forRootAsync({
useClass: MongooseConfigService,
})
service looks like this:
#Injectable({ scope: Scope.REQUEST })
export class MongooseConfigService implements MongooseOptionsFactory {
constructor(#Inject(REQUEST) private readonly request: Request) {}
async createMongooseOptions(): Promise<MongooseModuleOptions> {
if (Buffer.isBuffer(this.request.body)) {
this.request.body = JSON.parse(this.request.body.toString());
}
const { db } = this.request.body;
console.log('connecting database', db);
return {
uri: process.env.MONGO_URL,
dbName: db || '',
};
}
}
I understand we need to reuse the same connection. We have achieved it in nodejs by simply checking if the connection already exists and if it does not connect again. Not sure how to achieve the same in nest.js
tried changing the scope of service to Scope.DEFAULT but that didn't help.
I would suggest that you make a connection proxy for MongoDB. Ever time a lambda gets invoked, it will open up a new connection to MongoDB. AWS generally provides a service that allows you to proxy requests through one connect, this is a common issue with RDS etc.
This may help you though: https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda/
We were able to resolve the issue by using a durable provider. NestJs documentation we created a strategy at the root that would use a parameter coming in each request. NestJs would than call the connection module only when a new connection was required.
Note: When you use durable providers, Requests doesn't have all the parameters anymore and now only has the tenantId as per the example.
I have promoted my app from dev to stage environment App Service.
But now I cant see Page views,Custom events getting logged in my Application Insights which was logging fine in Dev.
Why is this happening?
Note:
1.I am using correct Instrumentation Key
2.Track calls are 200
3.The app is a Teams tab app built using React and using React plugin for App insights(working fine in dev)
4.Runtime Stack for dev environment was Node.Js but for Stage is .NET (Is this causing this issue?)
Also Note I have gone through all scenarios in Troubleshooting guide
Did the issue resolved for you ?
If not,
Ensure that you install the npm package for React.js,
npm install #microsoft/applicationinsights-react-js
npm install #microsoft/applicationinsights-web
Initialize a connection to Application Insights:
in AppInsights.js
import { ApplicationInsights } from '#microsoft/applicationinsights-web';
import { ReactPlugin } from '#microsoft/applicationinsights-react-js';
import { createBrowserHistory } from 'history';
const browserHistory = createBrowserHistory({ basename: '' });
const reactPlugin = new ReactPlugin();
const appInsights = new ApplicationInsights({
config: {
instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE',
extensions: [reactPlugin],
extensionConfig: {
[reactPlugin.identifier]: { history: browserHistory }
}
}
});
appInsights.loadAppInsights();
export { reactPlugin, appInsights };
And then Wrap your component with the higher-order component function to enable Application Insights on it:
import React from 'react';
import { withAITracking } from '#microsoft/applicationinsights-react-js';
import { reactPlugin, appInsights } from './AppInsights';
// To instrument various React components usage tracking, apply the `withAITracking` higher-order
// component function.
class MyComponent extends React.Component {
...
}
// withAITracking takes 4 parameters ( reactPlugin, Component, ComponentName, className)
// the first two are required and the other two are optional.
export default withAITracking(reactPlugin, MyComponent);
This will help you track all the requests, page views and custom events.
Also take a look at this doc for more reference : Javascript React SDK Plugin
Turns out it was a problem with the Application Insights instance itself and not in code or App service configuration.
When ever you face such problem where problem is not with code or App service,please reach out to your organization's support Team.
I am really new to Angular. I am trying to create a service which i want to consume in my angular component. While doing so i am getting below error.
Below is my code which i am writing
import { Injectable } from '#angular/core';
import { HttpClient} from '#angular/common/http';
import { CosmosClient } from '#azure/cosmos';
import {Observable,of} from 'rxjs'
#Injectable({
providedIn: 'root'
})
export class ApiService {
databaseId='dbName';
containerId='Container Name';
constructor() { }
public async getProjects():Promise<Observable<any>>{
const endpoint = "https://AAAA.documents.azure.com:443/";
const key = "==";
const client = new CosmosClient({ endpoint, key });
const database = client.database(this.databaseId);
const container = database.container(this.containerId);
const querySpec = {query: "SELECT * from c where c.Category=\"Details\""};
const { resources:items } = await container.items.query(querySpec).fetchAll();
return of(items);
}
}
Any help is really appreciated.
There is an exception to every rule, but the use cases for connecting to a DB directly from a web browser are pretty close to zero. By doing so, you lose all fine grained control over what a user can do in your database and the only way to revoke access is to rotate your keys. You may not currently have anything in your database that is sensitive, but it is still considered bad practice.
For this reason, the CosmosDB library is compatible with NodeJS as a server-side framework. Whether or not it works with front end frameworks like Angular or React are incidental. There are some large changes in how Angular compiles projects in version 9, and it looks like the Cosmos client is not compatible with the new Ivy compiler.
You do have a couple options here.
(recommended) Use an API layer between your database and your front end. You can use Node to keep it within Javascript. If you are running on Azure, there are services like Azure Functions that can make this even easier to implement securely, or you can run it from the same App Service, VM, or whatever hosting solution you are using.
Disable the new Ivy compiler.You can do this by adding aot: false in your angular.json
I am from .net background and few days back started using nestjs for one of my project.
I love the way nestjs built but few question here.
When using .net I can easily connect .net application with database by using some ORM like Ado.net, EF etc.
How do I connect nestjs with Postgres or SQL Server database?
Whatever will be the answer I would also like to know will that be suitable for enterprise applications?
Is there any reference site?
Thanks in advance
The docs show examples of how to conenct to a database using TypeORM and Sequilize, or you can roll your own dynamic module with custom providers if you want to use something else. There are a few packages around for knex, pg-promise, and massiveORM. These should all be more than suitable for enterprise applications, but if anything shows up as an issue, make sure to notify the owners of the repository.
Here is the basic structure I created to set up my current project with NestJS and PostgreSQL just in case this helps.
I added the following packages:
$ npm install --save knex objection objection-graphql pg
Created the nest database module and added this module to the "imports" and "exports" within the app.module.ts:
./src/database/database.module.ts
Then added the following files and folders:
./src/database/migrations
./src/database/models
./src/database/base.model.ts
./src/database/user.model.ts
./src/database/seeds
./src/database/migration.stub
./src/database/seed.stub
At the root level, I placed the knexfile.ts
import 'dotenv/config';
import Knex from 'knex';
import { knexSnakeCaseMappers } from 'objection';
module.exports = {
development: {
client: 'pg',
connection: process.env.DATABASE_URL,
migrations: {
directory: './src/database/migrations',
stub: './src/database/migration.stub',
},
seeds: {
directory: './src/database/seeds',
stub: './src/database/seed.stub'
},
...knexSnakeCaseMappers()
},
production: {
client: 'pg',
connectio: process.env.DATABASE_URL,
migrations: {
directory: __dirname + '/database/migrations',
},
seeds: {
directory: __dirname + '/database/seeds/production',
},
},
} as Knex.Config;
Then for each new Module, I called the model from the database folder
import { UserModel } from '../database/models/user.model'
That's it. Here you have connected PostgreSQL with NestJS.
As others have mentioned the NestJS manual is a well written resource for a detailed reference.
RON
Last year when I worked on building an Alexa skill, this is how I used to define a service:
service.ts
var createReport = function(variable,callback){
//Method code here
};
module.exports.createReport = createReport;
And this is how I used to call it in the :
app.ts
const service= require('../service.ts');
servicee.createReport (name,function=> {
//Callback function code here
}
)
This year I am building an Angular app in which services manipulation is different from the previous example.
Here's an example for state management service in my angular app:
service.ts
import { Injectable } from "#angular/core";
import { BehaviorSubject } from "rxjs";
#Injectable()
export class listOfThirdPartiesService {
constructor() {}
/************************************************** */
private listOfThirdPartiesValuesSource = new BehaviorSubject<string[][]>([
['','','','','','','',''],
['','','','','','','',''],
['','','','','','','',''],
['','','','','','','',''],
['','','','','','','',''],
['','','','','','','',''],
['','','','','','','',''],
['','','','','','','',''],
]);
currentListOfThirdParties = this.listOfThirdPartiesValuesSource.asObservable();
/************************************************************************ */
}
And this is how I I call it in the :
app.ts
import { listOfThirdPartiesService } from "../services/listOfThirdPartiesService.service";
Also in app.module.ts, I have to declare it in the providers.
So my questions are:
What is the difference between the two ways of implementing a service?
And in which use cases can I use the first one and the second one?
Take a look at this documentation on Services
You can simple create a service in Angular 2+ and above using the below command
ng generate service your-service
or simply
ng g s your-service
The above command automatically register your service into the module as well.
Now if you specify your service in providers in NgModule like as shown below, then it will be available to all components in that NgModule
#NgModule({
providers: [
YourService,
],
...
})
But if you want to use your service specifically only for some components the specify it under providers in your component
#Component({
selector: 'app-test',
templateUrl: './app-test.component.html',
providers: [ YourService ]
})
The first method, to me, seems to be just defining a function. This provides a functionality, and a closure. This isn't really a "Service".
The second method (using the #Injectable() decorator), make the class, well, injectable. This means that it will play with Angular's DI system. You can inject it into other Angular classes (Components and Services) by passing it in the constructor along with the typescript type. The Angular compiler will look to its providers and find a service of this type and you will have access to that exact instantiation of the class. You say that you are providing this in the AppModule. This means you are providing this in the root of the app and this service will be a singleton. In effect this method is the most convenient. I try to explain this with images in my half baked blog.
With the first method, if you care about how many instantiations you have, and which instance you are interacting with at any given time, you will need to watch how you are importing it, and if you are code-splitting.