I get a types error when registering redis with nestjs using CacheModule.register - redis

I am trying to implement redis using the packages : "CacheModule" and "cache-manager-redis-store". The latter brings me a type error when assigning it to the store property of the register method of CacheModule.
code where the error occurs:
`
import { Module, CacheModule } from "#nestjs/common";
import { AuthModule } from "./auth/auth.module";
import { MongooseModule } from "#nestjs/mongoose";
import { EnvConfiguration } from "./config/env.config";
import { ConfigModule } from "#nestjs/config";
import { redisStore } from "cache-manager-redis-store";
#Module({
imports: [
ConfigModule.forRoot({
load: [EnvConfiguration],
}),
MongooseModule.forRoot(process.env.MONGODB),
AuthModule,
CacheModule.register({
store: redisStore, <--- HERE THE ERROR HAPPENS
host: "localhost",
port: 6379,
}),
],
controllers: [],
providers: [],
})
export class AppModule {}
`
ERROR:
`
(property) store: (string | CacheStoreFactory | CacheStore) & ((config: RedisClientOptions<RedisModules, RedisFunctions, RedisScripts> & Config) => Promise<...>)
Cache manager. The default value is 'memory' (memory storage). See Different Stores for more information.
Type '(config: RedisClientOptions<RedisModules, RedisFunctions, RedisScripts> & Config) => Promise<RedisStore>' cannot be assigned to type '(string | CacheStoreFactory | CacheStore) & ((config: RedisClientOptions<RedisModules, RedisFunctions, RedisScripts > & Configuration) => Promise<...>)'.
Type '(config: RedisClientOptions<RedisModules, RedisFunctions, RedisScripts> & Config) => Promise<RedisStore>' cannot be assigned to type 'string & ((config: RedisClientOptions<RedisModules, RedisFunctions, RedisScripts> & Config) => Promise<...>)'.
Type '(config: RedisClientOptions<RedisModules, RedisFunctions, RedisScripts> & Config) => Promise<RedisStore>' cannot be assigned to type 'string'.ts(2322)
`
I want to be able to implement redis with nestjs, solving the described problem or with another way of implementing it that works correctly.

Change this:
import { redisStore } from "cache-manager-redis-store";
to this:
import redisStore from "cache-manager-redis-store";
or this:
import * as redisStore from "cache-manager-redis-store";
or this:
// eslint-disable-next-line #typescript-eslint/no-var-requires
const redisStore = require("cache-manager-redis-store");

The method of importing redisStore is the problem. The location pointed out as the issue is where the error is being generated.
From Nest JS Docs
import type { ClientOpts } from 'redis';
import * as redisStore from 'cache-manager-redis-store';
import { CacheModule, Module } from '#nestjs/common';
import { AppController } from './app.controller';
#Module({
imports: [
CacheModule.register<ClientOpts>({
store: redisStore,
// Store-specific configuration:
host: 'localhost',
port: 6379,
}),
],
controllers: [AppController],
})
export class AppModule {}

Related

How to test email sending with Mailhog on local?

Setup mailhog with docker-compose like:
version: '3'
services:
mailhog:
image: mailhog/mailhog
ports:
- 8025:8025
- 1025:1025
It's possible to access localhost:8025 from browser. Maybe the SMTP server 1025 also works but don't know how to confirm it.
In a NestJS application, for testing the email code as:
#Module({
imports: [NodeMailerModule],
providers: [MailHogEmailRepository],
exports: [MailHogEmailRepository],
})
class MailHogEmailRepositoryModule {}
#Module({
imports: [MailHogEmailRepositoryModule],
providers: [
{
provide: EmailRepository,
useFactory: (
config: ConfigService,
mailHog: MailHogEmailRepository,
) => {
return mailHog;
}
},
inject: [ConfigService, MailHogEmailRepository],
},
],
exports: [EmailRepository],
})
export class EmailRepositoryModule {}
MailHogEmailRepository send with nodemailer:
#Injectable()
export class MailHogEmailRepository implements EmailRepository {
constructor(
#Inject(NodeMailerToken) private readonly nodemailer: Transporter,
) {}
async send(email: Email) {
const options = {
to: email.to,
from: email.from,
subject: email.subject,
};
await this.nodemailer.sendMail(options);
}
}
nodemailer config:
import { Module } from '#nestjs/common';
import { ConfigService } from '#nestjs/config';
import { createTransport } from 'nodemailer';
export const NodeMailerToken = Symbol('nodemailer');
#Module({
providers: [
{
provide: NodeMailerToken,
useFactory: (config: ConfigService) =>
createTransport({
host: 'localhost',
port: 1025,
secure: true,
}),
inject: [ConfigService],
},
],
exports: [NodeMailerToken],
})
export class NodeMailerModule {}
In test source, it always timeout:
import { Test, TestingModule } from '#nestjs/testing';
import request from 'supertest';
import {
FastifyAdapter,
NestFastifyApplication,
} from '#nestjs/platform-fastify';
describe('Test sender', () => {
let app: NestFastifyApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication(new FastifyAdapter());
await app.init();
await app.getHttpAdapter().getInstance().ready();
});
describe('/handler (POST)', () => {
describe('should send data to mail server', () => {
it('success', () => {
const message = ...
return request(app.getHttpServer())
.post('/handler')
.send({ message })
.expect(200);
});
});
});
});
$ npm run test
thrown: "Exceeded timeout of xxx ms for a test.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
It seems the test case couldn't access the mailhog server running in docker container. How to set it correctly?

Adding serialport and usb in NestJS?

Is it possible to add a serial port and USB package in NestJS? I can't seem to find anything regarding these things.
In your serial.module.ts, create your custom serial handler service by custom factory providers
import { SerialHandlerService } from './serial-handler.service';
#Module({
providers: [
{
provide: 'SerialHandlerService',
useFactory: SerialHandlerService,
},
],
})
export class SerialModule {}
Create serial-handler.service.ts in same folder
import * as SerialPort from 'serialport';
const Readline = SerialPort.parsers.Readline;
export const SerialHandlerService = () => {
const port = new SerialPort(
{YOUR_SERIAL_PORT},
{
baudRate: {YOUR_SERIAL_BOADRATE},
dataBits: {YOUR_SERIAL_DATABITS},
stopBits: {YOUR_SERIAL_STOPBITS},
parity: {YOUR_SERIAL_PARITY},
},
(err) => {
if (err) {
console.error(err)
// Handle Error
}
console.log('success')
},
);
// I'm using Readline parser here. But, You can change parser that you want!
const parser = new Readline({ delimiter: '\r\n' });
port.pipe(parser);
port.on('open', () => {
console.info('port opened');
});
parser.on('data', (data) => {
console.log(data);
// Data is string, process your data below!
}
}
Add your serial.module.ts in your app.module.ts
#Module({
imports: [
// your other modules...
SerialModule,
],
controllers: [],
providers: [],
})
export class AppModule {}
[Reference: https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory]

Angular 8 testing error Unexpected value 'DecoratorFactory' imported by the module 'DynamicTestModule'

I am trying to make Jasmine & Karma framework into the current angular application running in ver 8.2. But i am coming across this weird error inside the Karma test running window:
Failed: Unexpected value 'DecoratorFactory' imported by the module 'DynamicTestModule'. Please add a #NgModule annotation.
What is the problem?
My componenent.spec.ts looks like this:
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { HomeComponent } from './home.component';
import { NO_ERRORS_SCHEMA} from '#angular/core';
import {RouterTestingModule} from '#angular/router/testing';
import {HttpClientTestingModule} from '#angular/common/http/testing';
import { MsalService } from '#azure/msal-angular';
import { Store } from '#ngrx/store';
import { Pipe } from '#angular/core';
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule, HttpClientTestingModule, Pipe]
,declarations: [HomeComponent]
,schemas:[NO_ERRORS_SCHEMA]
,providers: [
{provide: MsalService, useFactory: '' },
{provide: Store, useFactory: '' }
]
})
.compileComponents();
}));
it('should have header text', async(() => {
const fixture = TestBed.createComponent(HomeComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
//expect(compiled.querySelector('.header-txt').textContent).toContain('Tax');
}));
});
I found the cause :-
export class MockStore<T> {
private state: BehaviorSubject<T> = new BehaviorSubject(undefined);
setState(data: T) { this.state.next(data); }
select(selector?: any): Observable<T> {
return this.state.asObservable();
}
pipe() {}
dispatch(action: any) { }
}
========================================================================
TestBed.configureTestingModule({
{provide: Store, useFactory: 'MockStore' }
..............
The useFactory property must be some custom class name. Now i mocked the store class.

Store a value in redis store using Nestjs

I have a simple nestjs application, where I have set up a CacheModule using Redis store as follows:
import * as redisStore from 'cache-manager-redis-store';
CacheModule.register({
store: redisStore,
host: 'redis',
port: 6379,
}),
I would like to use it to store a single value, however, I do not want to do it the built-in way by attaching an interceptor to a controller method, but instead I want to control it manually and be able to set and retrieve the value in the code.
How would I go about doing that and would I even use cache manager for that?
You can use the official way from Nest.js:
1. Create your RedisCacheModule:
1.1. redisCache.module.ts:
import { Module, CacheModule } from '#nestjs/common';
import { ConfigModule, ConfigService } from '#nestjs/config';
import * as redisStore from 'cache-manager-redis-store';
import { RedisCacheService } from './redisCache.service';
#Module({
imports: [
CacheModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
store: redisStore,
host: configService.get('REDIS_HOST'),
port: configService.get('REDIS_PORT'),
ttl: configService.get('CACHE_TTL'),
}),
}),
],
providers: [RedisCacheService],
exports: [RedisCacheService] // This is IMPORTANT, you need to export RedisCacheService here so that other modules can use it
})
export class RedisCacheModule {}
1.2. redisCache.service.ts:
import { Injectable, Inject, CACHE_MANAGER } from '#nestjs/common';
import { Cache } from 'cache-manager';
#Injectable()
export class RedisCacheService {
constructor(
#Inject(CACHE_MANAGER) private readonly cache: Cache,
) {}
async get(key) {
await this.cache.get(key);
}
async set(key, value) {
await this.cache.set(key, value);
}
}
2. Inject RedisCacheModule wherever you need it:
Let's just assume we will use it in module DailyReportModule:
2.1. dailyReport.module.ts:
import { Module } from '#nestjs/common';
import { RedisCacheModule } from '../cache/redisCache.module';
import { DailyReportService } from './dailyReport.service';
#Module({
imports: [RedisCacheModule],
providers: [DailyReportService],
})
export class DailyReportModule {}
2.2. dailyReport.service.ts
We will use the redisCacheService here:
import { Injectable, Logger } from '#nestjs/common';
import { Cron } from '#nestjs/schedule';
import { RedisCacheService } from '../cache/redisCache.service';
#Injectable()
export class DailyReportService {
private readonly logger = new Logger(DailyReportService.name);
constructor(
private readonly redisCacheService: RedisCacheService, // REMEMBER TO INJECT THIS
) {}
#Cron('0 1 0 * * *') // Run cron job at 00:01:00 everyday
async handleCacheDailyReport() {
this.logger.debug('Handle cache to Redis');
}
}
You can check my sample code here.
Building on Ahmad's comment above, I used the following to enable redis in my nestjs application:
Install and setup nestjs-redis https://www.npmjs.com/package/nestjs-redis per docs.
See the docs here on how to write and read values in a Redis store:
https://github.com/NodeRedis/node-redis
If you're connection a external Redis, I recommend to use 'async-redis' package.
The code will be:
import * as redis from 'async-redis';
import redisConfig from '../../config/redis';
On redisConfig:
export default {
host: 'your Host',
port: parseInt('Your Port Conection'),
// Put the first value in hours
// Time to expire a data on redis
expire: 1 * 60 * 60,
auth_pass: 'password',
};
So, you run:
var dbConnection = redis.createClient(config.db.port, config.db.host,
{no_ready_check: true});
Now you can, execute commands like set and get for your Redis Database.

Using AlarmService Throws different Errors in angular 6 TypeScript

I'm having some problem in resolving this error. When i add the Alarmservice i always get this error.
When i checked this error in google, every one say, i have to add this in provider, If i add in provider also it is not working and i get a different error
import { Component, Input } from '#angular/core';
import { Client, BasicAuth, AlarmService } from '#c8y/client';
import { CumulocityService } from './c8y.service';
import {
Router
} from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
#Input() name: string;
model = {
user: '',
password: '',
tenant: ''
};
error = {
shown: false,
msg: ''
};
disabled = false;
basicAuth: string = 'https://tempar.adamos.com'
currentUser: object = {};
constructor(
private cumulocity: CumulocityService,
private alarmService: AlarmService,
private route: Router
) { }
async login() {
this.disabled = true;
const client = new Client(new BasicAuth(
{
user: this.model.user,
password: this.model.password,
tenant: this.model.tenant
}),
this.basicAuth
);
sessionStorage.setItem("client", JSON.stringify(client));
client.inventory.list$().subscribe((data) => {
// request all inventory data via fetch and adds realtime if data changes
console.log(data);
});
try {
let user = await client.user.current();
debugger;
this.cumulocity.client = client;
console.log(user.data);
const alarmId: number = 63704;
const { data, res } = await this.alarmService.detail(alarmId);
console.log(data, res);
// this.route.navigate(['/dashboard']);
} catch (ex) {
this.cumulocity.client = null;
this.error.shown = true;
this.error.msg = ex.message;
} finally {
this.disabled = false;
}
}
}
core.js:1673 ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[LoginComponent -> AlarmService]:
StaticInjectorError(Platform: core)[LoginComponent -> AlarmService]:
NullInjectorError: No provider for AlarmService!
Error: StaticInjectorError(AppModule)[LoginComponent -> AlarmService]:
StaticInjectorError(Platform: core)[LoginComponent -> AlarmService]:
NullInjectorError: No provider for AlarmService!
at NullInjector.push../node_modules/#angular/core/fesm5/core.js.NullInjector.get (core.js:1062)
at resolveToken (core.js:1300)
at tryResolveToken (core.js:1244)
at StaticInjector.push../node_modules/#angular/core/fesm5/core.js.StaticInjector.get (core.js:1141)
at resolveToken (core.js:1300)
at tryResolveToken (core.js:1244)
at StaticInjector.push../node_modules/#angular/core/fesm5/core.js.StaticInjector.get (core.js:1141)
at resolveNgModuleDep (core.js:8376)
at NgModuleRef_.push../node_modules/#angular/core/fesm5/core.js.NgModuleRef_.get (core.js:9064)
at resolveDep (core.js:9429)
at NullInjector.push../node_modules/#angular/core/fesm5/core.js.NullInjector.get (core.js:1062)
at resolveToken (core.js:1300)
at tryResolveToken (core.js:1244)
at StaticInjector.push../node_modules/#angular/core/fesm5/core.js.StaticInjector.get (core.js:1141)
at resolveToken (core.js:1300)
at tryResolveToken (core.js:1244)
at StaticInjector.push../node_modules/#angular/core/fesm5/core.js.StaticInjector.get (core.js:1141)
at resolveNgModuleDep (core.js:8376)
at NgModuleRef_.push../node_modules/#angular/core/fesm5/core.js.NgModuleRef_.get (core.js:9064)
at resolveDep (core.js:9429)
at resolvePromise (zone.js:814)
at resolvePromise (zone.js:771)
at zone.js:873
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:3815)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
at drainMicroTaskQueue (zone.js:595)
If i add Alarmservice at the app.module.ts I get a different error, as said above
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { CumulocityService } from './login/c8y.service';
import { AlarmService } from '#c8y/client';
#NgModule({
declarations: [
AppComponent,
LoginComponent,
DashboardComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [ AlarmService, CumulocityService],
bootstrap: [AppComponent]
})
export class AppModule { }
ERROR
Uncaught Error: Can't resolve all parameters for AlarmService: (?, ?).
at syntaxError (compiler.js:1016)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getDependenciesMetadata (compiler.js:10917)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getTypeMetadata (compiler.js:10810)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getInjectableTypeMetadata (compiler.js:11032)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getProviderMetadata (compiler.js:11041)
at compiler.js:10979
at Array.forEach (<anonymous>)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getProvidersMetadata (compiler.js:10939)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (compiler.js:10658)
at JitCompiler.push../node_modules/#angular/compiler/fesm5/compiler.js.JitCompiler._loadModules (compiler.js:23858)
Have you seen the stackblitz example? I guess you have because it looks like the code from there.
At the moment you cannot inject the services into angular directly. You can just write a wrapper around the client (like done in the example)
So to make your code working:
remove the AlarmService import
Request a alarm via this.client.alarm.detail(alarmId); instead of the AlarmService.
The this.client.alarm is of type AlarmService and uses the login you set via new Client(new BasicAuth([...]));.
In future, you can use #c8y/ngx-data to do proper dependency injection, but it is not released as stable and therefore I would not suggest to use it.