How to get logging on terminalthe raw query in prisma, nestjs? - prisma

How to get logging on terminalthe raw query in prisma, nestjs?
I am setting up for logging using prisma and nestjs.
in my code:
PrismaModule.forRoot({
isGlobal: true,
prismaServiceOptions: {
prismaOptions: { log: ['info', 'query']},
explicitConnect: true,
},
}),
this is logging middleware
import { Prisma } from '#prisma/client';
export function loggingMiddleware(): Prisma.Middleware {
return async (params, next) => {
const before = Date.now();
const result = await next(params);
const after = Date.now();
console.log(
`Query ${params.model}.${params.action} took ${after - before}ms`,
);
return result;
};
}
this is my prismaService
#Injectable()
export class PrismaService
extends PrismaClient<
Prisma.PrismaClientOptions,
'query | error | debug | info'
>
implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(PrismaService.name);
constructor() {
super({ log: [{ emit: 'event', level: 'query' }] });
this.logger.log(`Prisma v${Prisma.prismaVersion.client}`);
this.$on('query', (e) => this.logger.debug(`${e.query} ${e.params}`));
}
// constructor() {
// super({
// log: [
// { emit: 'event', level: 'query' },
// { emit: 'stdout', level: 'info' },
// { emit: 'stdout', level: 'warn' },
// { emit: 'stdout', level: 'error' },
// ],
// errorFormat: 'colorless',
// });
// }
async onModuleInit() {
await this.$connect();
}
async onModuleDestroy() {
await this.$disconnect();
}
async enableShutdownHooks(app: INestApplication) {
this.$on('beforeExit', async (event) => {
console.log(event.name);
await app.close();
});
}
}
I want to show raw query on terminal like TypeORM. But I can get anything on terminal.
How do I configure prisma logging correctly?

The simplest way to print all log levels to stdout is to pass in an array LogLevel objects:
const prisma = new PrismaClient({
log: ['query', 'info', 'warn', 'error'],
})
This is the short form of passing in an array of LogDefinition objects where the value of emit is always stdout:
const prisma = new PrismaClient({
log: [
{
emit: 'stdout',
level: 'query',
},
{
emit: 'stdout',
level: 'error',
},
{
emit: 'stdout',
level: 'info',
},
{
emit: 'stdout',
level: 'warn',
},
],
})
For more information on logging using Prisma, Please check the docs on logging.

Related

delete item from apiCall need reload page to deleted from client

i use redux toolkit with react native and mongodb (mongoose)
i delete item and it successfully deleted from db
but not in client and need to reload page
todoSlice :
import {createSlice} from '#reduxjs/toolkit';
export const todoSlice = createSlice({
name: 'todos',
initialState: {
todos: [],
pending: null,
error: null,
},
reducers: {
deleteTodo: (state, action) => {
return state
},
},
});
export const {deleteTodo} = todoSlice.actions;
export default todoSlice.reducer;
apiCall:
import axios from 'axios';
import {deleteTodo} from './todoSlice';
export const deleteOneTodo = async (id, dispatch) => {
try {
await axios.delete(`http://10.0.2.2:5000/todos/${id}`);
dispatch(deleteTodo());
} catch (err) {
console.log(err);
}
};
main :
const {todo} = useSelector(state => state);
const dispatch = useDispatch();
const {todos} = todo;
useEffect(() => {
getTodos(dispatch);
}, []);
const handleDelete = id => {
deleteOneTodo(id, dispatch);
};
you have to implement deleteTodo inside your todoSlice in order to remove the deleted id from your local state,
...
export const todoSlice = createSlice({
name: 'todos',
initialState: {
todos: [],
pending: null,
error: null,
},
reducers: {
deleteTodo: (state, action) => {
return state.filter((todo)=>todo.id!==action.payload.id);
},
},
});
...
and of course you have to pass the payload with the id of the todo you want to remove
export const deleteOneTodo = async (id, dispatch) => {
try {
await axios.delete(`http://10.0.2.2:5000/todos/${id}`);
dispatch(deleteTodo({id:id}));
} catch (err) {
console.log(err);
}
};
if you still have doubts you can follow this tutorial: https://www.youtube.com/watch?v=fiesH6WU63I
i just call 'getTodos' inside 'deleteOneTodo'
and delete 'deleteTodo' from reducer
i hope its a good practice
export const deleteOneTodo = async (id, dispatch) => {
try {
await axios.delete(`http://10.0.2.2:5000/todos/${id}`);
// i add this line =>
getTodos(dispatch);
} catch (err) {
console.log(err);
}
};

How to write Nestjs unit tests for #Injectable() mongodb service

Can someone please guide me. I'm learning Nestjs and doing a small project, and I'm not able to get the unit test working for a controller and service which has dependency on the database.module. How do I go about mocking the database.module in the product.service.ts? Any help will be highly appreciated.
database.module.ts
try {
const client = await MongoClient.connect(process.env.MONGODB, { useNewUrlParser: true, useUnifiedTopology: true });
return client.db('pokemonq')
} catch (e) {
console.log(e);
throw e;
}
};
#Module({
imports: [],
providers: [
{
provide: 'DATABASE_CONNECTION',
useFactory: setupDbConnection
},
],
exports: ['DATABASE_CONNECTION'],
})
export class DatabaseModule {}
product.service.ts
#Injectable()
export class ProductService {
protected readonly appConfigObj: EnvConfig;
constructor(
private readonly appConfigService: AppConfigService,
#Inject('DATABASE_CONNECTION') => **How to mock this injection?**
private db: Db,
) {
this.appConfigObj = this.appConfigService.appConfigObject;
}
async searchBy (){}
async findBy (){}
}
product.service.spec.ts
describe('ProductService', () => {
let service: ProductService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [],
providers: [
ConfigService,
DatabaseModule,
AppConfigService,
ProductService,
{
provide: DATABASE_CONNECTION,
useFactory: () => {}
}
],
}).compile();
service = module.get< ProductService >(ProductService);
});
afterAll(() => jest.restoreAllMocks());
}
product.controller.spec.ts
describe('ProductController', () => {
let app: TestingModule;
let ProductController: ProductController;
let ProductService: ProductService;
const response = {
send: (body?: any) => {},
status: (code: number) => response,
json: (body?: any) => response
}
beforeEach(async () => {
app = await Test.createTestingModule({
imports: [
ConfigModule.forRoot({
load: [appConfig],
isGlobal: true,
expandVariables: true
}),
ProductModule,
],
providers: [
AppConfigService,
ProductService,
],
controllers: [ProductController]
}).compile();
productController = app.get< ProductController >(ProductController);
productService = app.get< ProductService >(ProductService);
});
afterAll(() => jest.restoreAllMocks());
}
Anything that is not being tested directly in a unit test should theoretically be mocked. In this case, you have two dependencies, AppConfigService adn DATABASE_CONNECTION. You're unit test should provide mock objects that look like the injected dependencies, but have defined and easy to modify behavior. In this case, something like this may be what you're looking for
beforeEach(async () => {
const modRef = await Test.createTestingModule({
providers: [
ProductService,
{
provide: AppConfigService,
useValue: {
appConfigObject: mockConfigObject
}
},
{
provide: 'DATABASE_CONNECTION',
useValue: {
<databaseMethod>: jest.fn()
}
]
}).compile();
// assuming these are defined in the top level describe
prodService = modRef.get(ProductionService);
conn = modRef.get('DATABASE_CONNECTION');
config = modRef.get(AppConfigService);
});
In your controller test, you shouldn't worry about mocking anything other than the ProdctService.
If you need more help there's a large repository of examples here
Edit 9/04/2020
Mocking chained methods is a major pain point when working with things like Mongo. There's a few ways you can go about it, but the easiest is probably to create a mock object like
const mockModel = {
find: jest.fn().mockReturnThis(),
update: jest.fn().mockReturnThis(),
collation: jest.fn().mockReturnThis(),
...etc
}
And on the last call in the chain, make it return the expected outcome so your service can keep running the rest of the code. This would mean if you have a call like
const value = model.find().collation().skip().limit().exec()
you would need to set the exec() method to return the value you expect it to, probably using something like
jest.spyOn(mockModel, 'exec').mockResolvedValueOnce(queryReturn);
I am also exploring using native Mongodb with NestJS. Below is my working test for cron job service updating value in db.
src/cron/cron.service.ts
import { Inject, Injectable } from '#nestjs/common';
import { Cron, CronExpression } from '#nestjs/schedule';
import { Db } from 'mongodb';
import { Order } from 'src/interfaces/order.interface';
#Injectable()
export class CronService {
constructor(
#Inject('DATABASE_CONNECTION')
private db: Db,
) {}
#Cron(CronExpression.EVERY_30_SECONDS)
async confirmOrderEveryMinute() {
console.log('Every 30 seconds');
await this.db
.collection<Order>('orders')
.updateMany(
{
status: 'confirmed',
updatedAt: {
$lte: new Date(new Date().getTime() - 30 * 1000),
},
},
{ $set: { status: 'delivered' } },
)
.then((res) => console.log('Orders delivered...', res.modifiedCount));
}
}
src/cron/cron.service.spec.ts
import { Test, TestingModule } from '#nestjs/testing';
import { Db } from 'mongodb';
import { CronService } from './cron.service';
describe('CronService', () => {
let service: CronService;
let connection: Db;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
CronService,
{
provide: 'DATABASE_CONNECTION',
useFactory: () => ({
db: Db,
collection: jest.fn().mockReturnThis(),
updateMany: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
}),
},
],
}).compile();
service = module.get<CronService>(CronService);
connection = module.get('DATABASE_CONNECTION');
});
it('should be defined', async () => {
expect(service).toBeDefined();
});
it('should confirmOrderEveryMinute', async () => {
await service.confirmOrderEveryMinute();
expect(connection.collection('orders').updateMany).toHaveBeenCalled();
});
});

ERROR in Read query using n AWS AppSync Chat Starter App written in Angular "Can't find field allMessageConnection"

const message: Message = {
conversationId: conversationId,
content: this.message,
createdAt: id,
sender: this.senderId,
isSent: false,
id: id,
};
this.appsync.hc().then((client) => {
client
.mutate({
mutation: createMessage,
variables: message,
optimisticResponse: () => ({
createMessage: {
...message,
__typename: "Message",
},
}),
update: (proxy, { data: { createMessage: _message } }) => {
const options = {
query: getConversationMessages,
variables: {
conversationId: conversationId,
first: constants.messageFirst,
},
};
// error on below line
const data = proxy.readQuery(options);
const _tmp = unshiftMessage(data, _message);
proxy.writeQuery({ ...options, data: _tmp });
},
})
.then(({ data }) => {
console.log("mutation complete", data);
console.log("mutation complete", data);
})
.catch((err) => console.log("Error creating message", err));
});
Analytics.record("Chat MSG Sent");
}
ERROR
errorHandling.js:7 Error: Can't find field allMessageConnection({"conversationId":"XXXXXXXXXXXXXXXXXXXXXXXXXXX","first":100}) on object {
"me": {
"type": "id",
"generated": false,
"id": "User:XXXXXXXXXXXXXXXXXXX",
"typename": "User"
}
}.

trying to connect graphql to postgress how to define user and pass?

I fail to receive information from my postgres db when trying to connect with graphql.
I receive the following response:
{
"errors": [
{
"message": "password authentication failed for user \"admin\"",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"account"
]
}
],
"data": {
"account": null
}
}
I honestly don't know where to define the user and pass.
const express = require('express');
const expressGraphQL = require('express-graphql');
const schema = require('./schema');
const app = express();
app.use('/graphql', expressGraphQL({
schema,
graphiql: true
}))
app.listen(4000, () => {
console.log('Listening...')
})
and this is my schema file
const graphql = require('graphql');
const connectionString = 'myURI';
const pgp = require('pg-promise')();
const db = {}
db.conn = pgp(connectionString);
const {
GraphQLObjectType,
GraphQLID,
GraphQLString,
GraphQLBoolean,
GraphQLList,
GraphQLSchema
} = graphql;
const AccountType = new GraphQLObjectType({
name: 'account',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
busines_name: { type: GraphQLString },
email: {
type: new GraphQLList(EmailType),
resolve(parentValue, args) {
const query = `SELECT * FROM "emails" WHERE
account=${parentValue.id}`;
return db.conn.many(query)
.then(data => {
return data;
})
.catch(err => {
return 'The error is', err;
});
}
}
})
})
const EmailType = new GraphQLObjectType({
name: 'Email',
fields: {
id: { type: GraphQLID },
email: { type: GraphQLString },
primary: { type: GraphQLBoolean }
}
})
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
account: {
type: AccountType,
args: { id: { type: GraphQLID } },
resolve(parentValue, args) {
const query = `SELECT * FROM "account" WHERE id=${args.id}`;
return db.conn.one(query)
.then(data => {
return data;
})
.catch(err => {
return 'The error is', err;
});
}
},
emails: {
type: EmailType,
args: { id: { type: GraphQLID } },
resolve(parentValue, args) {
const query = `SELECT * FROM "emails" WHERE id=${args.id}`;
return db.conn.one(query)
.then(data => {
return data;
})
.catch(err => {
return 'The error is', err;
});
}
}
}
})
module.exports = new GraphQLSchema({
query: RootQuery
})
I would like to know where to define the user and the password for the db of what i'm doing wrong besides that.
const connectionString = 'myURI';
It should be enough if your connection string includes the username and password. Is your DB connection string of the form postgres://username:password#server:5432 ?
See https://www.postgresql.org/docs/10/libpq-connect.html#LIBPQ-CONNSTRING

Stub mongoDB with hapijs

I'm trying to figure out how to stub mongoDB in hapi js to allow testing but I have no idea how to do it. I've tried checking out Sinonjs but I have no idea how to apply it in this particular case.
Here's some of the code:
// index.js
'use strict';
const Hapi = require('hapi');
const MongoJS = require('mongojs');
const server = new Hapi.Server();
server.connection({ host: 'localhost', port: 11001 });
server.app.db = MongoJS('crunchbase', ['companies']);
server.register([
{
register: require('./lib/plugins')
},
{
register: require('./lib/modules/companies'),
options: {
baseUrl: '/v1/companies'
}
}
], (err) => {
if (err) {
throw err;
}
server.start((err) => {
if (err) {
throw err;
}
server.log('info', `Server listening on ${server.info.uri}`);
});
});
module.exports = server;
Here's are the routes:
// companies.js
'use strict';
const Boom = require('boom');
const Joi = require('joi');
const error = Joi.object().keys({
statusCode: Joi.number(),
error: Joi.string(),
message: Joi.string()
});
const schema = Joi.object().keys({
_id: Joi.object(),
permalink: Joi.string(),
name: Joi.string(),
homepage_url: Joi.string(),
category_list: Joi.string(),
funding_total_usd: Joi.alternatives().try(Joi.number(), Joi.string()),
status: Joi.string(),
country_code: Joi.string().allow(''),
state_code: Joi.alternatives().try(Joi.string(), Joi.number()).allow(''),
region: Joi.string().allow(''),
city: Joi.string().allow(''),
funding_rounds: Joi.number(),
founded_at: Joi.string().allow(''),
first_funding_at: Joi.string(),
last_funding_at: Joi.string()
});
exports.register = (server, options, next) => {
const db = server.app.db;
const { baseUrl } = options;
server.route([
{
method: 'GET',
path: baseUrl,
config: {
description: 'companies',
notes: 'Get a list of companies from the database',
tags: ['api'],
validate: {
query: {
limit: Joi.number().min(1).max(20).default(5)
}
},
response: {
status: {
200: Joi.array().items(schema),
400: error,
500: error
}
}
},
handler: (request, reply) => {
db.companies.find().limit(request.query.limit, (err, docs) => {
if (err) {
return reply(Boom.wrap(err, 'Internal MongoDB error.'));
}
reply(docs);
});
}
}
]);
return next();
};
exports.register.attributes = {
pkg: require('./package.json')
};
And here's the test suite:
// companies.test.js
'use strict';
const Code = require('code');
const Lab = require('lab');
const lab = exports.lab = Lab.script();
const { describe, it } = lab;
const expect = Code.expect;
const Server = require('../../');
describe('Companies module test suite', () => {
const baseUrl = '/v1/companies';
it('should return array of 5 companies by default', (done) => {
Server.inject({
method: 'GET',
url: baseUrl
}, (response) => {
expect(response.statusCode).to.equal(200);
expect(response.result).to.be.an.array().and.have.length(5);
done();
});
});
it('should return array of 3 companies', (done) => {
Server.inject({
method: 'GET',
url: baseUrl + '?limit=3'
}, (response) => {
expect(response.statusCode).to.equal(200);
expect(response.result).to.be.an.array().and.have.length(3);
done();
});
});
it('should throw an error', (done) => {
Server.inject({
method: 'GET',
url: baseUrl + '?limit=me'
}, (response) => {
expect(response.statusCode).to.equal(400);
expect(response.result.error).to.equal('Bad Request');
done();
});
});
});
It works but only if there's a connection to the db which I want to decouple. Any help would be appreciated.
Here's a solution courtesy of devinivy
One approach I've taken is to place queries in server methods, then
stub out the server methods (server.methods.x = stubX) in my tests.
You could also check out proxyquire as suggested by timcosta
Here's the brief github discussion