Showing posts with label Nest Js. Show all posts
Showing posts with label Nest Js. Show all posts

Monday, 20 March 2023

mocker data generator using nodejs

 fake data generator using node.js

 synthetic data generation using nodejs

Help link

https://www.npmjs.com/package/mocker-data-generator

https://chancejs.com/


https://phaker.js.org/


https://fakerjs.dev/



test_data_generator.js

var mocker = require('mocker-data-generator').default // (vanilla way)
const { faker } = require('@faker-js/faker');

var users = {
firstName: {
faker: 'name.firstName()'
},
lastName: {
faker: 'name.lastName()'
},
country: {
faker: 'address.country()'
},
city: {
faker: 'address.city()'
},
// description: {
// faker: 'lorem.paragraph()'
// },
createdAt: {
faker: 'date.past()'
},
id: {
incrementalId: 0
},
age: {
faker: 'datatype.number({"min": 18, "max": 30})'
//faker: 'random.numeric(2,{"min": 1, "max": 17})'
},
birthdate:{
faker:'date.birthdate({ "min": 10, "max": 20, "mode": "age" })'
},
user_group:{
values:
['Primary Owner', 'Owner', 'Admin','Editor','Contributor','Viewer','Billing']
},
emails:
{
faker: 'internet.email()'
}
,
// emails: [
// {
// faker: 'internet.email()',
// length: 1
// }
// ],
username: {
function: function () {
return (
this.object.lastName.substring(0, 5) +
this.object.firstName.substring(0, 3) +
Math.floor(Math.random() * 10)
)
}
},
phone_number:{
faker:"phone.number('+91 97 ### ### ##')"
},
account_balance:{
faker:"finance.amount()"
},
currencyCode:{
faker:'finance.currencyCode()'
},
account_number:{
faker:'finance.account()'
},
accountName:{
faker:'finance.accountName()'
},
creditCardCVV:{
faker:'finance.creditCardCVV()'
},
creditCardIssuer:{
faker:'finance.creditCardIssuer()'
},
creditCardNumber:{
faker:"finance.creditCardNumber('63[7-9]#-####-####-####')"
},
last_login_ip4:{
faker:"internet.ipv4()"
},
last_login_ip6:{
faker:"internet.ipv6()"
},
get: {
function() {
return this.object.emails[0]
}
}
}


var house = {
id: {
incrementalId: 0
},
address: {
faker: 'address.streetAddress'
},
householder: {
hasOne: 'users'
},
// mateIds: {
// hasMany: 'users',
// max: 2,
// min: 2,
// unique: true
// }
};

console.time('bench')
mocker()
.addGenerator('faker', faker)
.schema('users', users, 10)
.schema('cat2', users, { uniqueField: 'user_group' })
.schema('houses', house, 5)
.build(function (err, data) {
console.log(err)
console.timeEnd('bench')
console.log(JSON.stringify(data));
})


package.json
{
"name": "mocker-data-generator",
"version": "1.0.0",
"dependencies": {
"ava": "^5.1.0",
"casual-browserify": "^1.5.19",
"chance": "^1.1.7",
"codecov": "^3.8.2",
"conventional-github-releaser": "^3.1.5",
"gh-pages": "^4.0.0",
"http-server": "^14.1.1",
"mocker-data-generator": "^3.0.1",
"multiview": "^3.0.1",
"npm-scripts-info": "^0.3.9",
"nyc": "^15.1.0",
"opn-cli": "^5.0.0",
"phaker.js": "^6.0.0-rc.1",
"prettier": "^2.8.1",
"randexp": "^0.5.3",
"standard-version": "^9.5.0",
"trash-cli": "^5.0.0",
"ts-node": "^10.9.1",
"tslib": "^2.4.1",
"tslint": "^6.1.3",
"tslint-config-standard": "^9.0.0",
"typedoc": "^0.23.23",
"typescript": "^4.9.4"
},
"devDependencies": {
"@faker-js/faker": "^7.6.0"
}
}

Saturday, 2 April 2022

mongoose full text search in nestjs


import * as mongoose from 'mongoose';
const SALT_ROUNDS = 10;

function transformValue(doc, ret: { [key: string]: any }) {
delete ret._id;
delete ret.password;
}

export interface IUserSchema extends mongoose.Document {
organizationId: string;
email:string,
password:string,
userRole:[],
status:string,
firstName:string,
lastName:string,
address:string,
}


export const UserSchema = new mongoose.Schema<IUserSchema>(
{
organizationId:{
type: String
},
email:{
type: String,
},
password: {
type: String
},
userRole: {
type: []
},
firstName: {
type: String
},
lastName: {
type: String
},
address: {
type: String
},
status: {
type: String
},
},
{
toObject: {
virtuals: true,
versionKey: false,
transform: transformValue,
},
toJSON: {
virtuals: true,
versionKey: false,
transform: transformValue,
},
},
);

UserSchema.index({ "$**": "text" },
{ name: "userTextIndex",locale: 'en', strength: 2}) //


in Your Nest Js Mongo Config Service look like import {
MongooseOptionsFactory,
MongooseModuleOptions,
} from '@nestjs/mongoose';

export class MongoConfigService implements MongooseOptionsFactory {
createMongooseOptions(): MongooseModuleOptions {
return {
uri: process.env.MONGO_DSN,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
};
}
}

db.getCollection('user').find({ $text: { $search: "activ"} }); mongoose full text search in nestjs
mongodb full text search in nodejs
mongodb full $text $search in nodejs
mongoose create text indexes




Saturday, 16 May 2020

Nest Js Serve Static File , Image and Download Pdf File



import { ControllerGetPostResParamReqHeader } from '@nestjs/common';
import { fsRoot } from './server-config';
import { createReadStream } from 'fs';
import { join } from 'path';
import url = require('url');

@Controller()
export class AppController {

    @Get('/upload/:fileId')
    async serveAvatar(@Param('fileId'fileId, @Res() res): Promise<any> {
        return res.sendFile(fileId, { root: 'upload' });
    }

// serve all nested folder
// @Get('/upload/*')
     // async serveAvatar(@Req() req, @Res() res): Promise<any> {
// const urlObject = url.parse(req.urltrue);
     //    const filePath = decodeURI(urlObject.path).replace('/api/upload/''');
     //    return res.sendFile(filePath , { root: 'upload' });
     // }


    @Get('/test')
    //@Header('Content-Type', 'application/pdf')
    getTest(@Res() response) {
        const url = join(fsRoot(), '/upload/test.pdf');
        const data = createReadStream(url);
        response.setHeader('Content-Type''application/pdf');
        response.setHeader('Content-Disposition''attachment; filename=another.pdf');
        data.pipe(response);
    }
}

// Create upload folder on your project root dir
// If you set app.setGlobalPrefix("api");
// image is serve on http://localhost:3000/api/upload/a.png
// pdf file is serve on http://localhost:3000/api/upload/test.pdf

// **************** server-config.ts Code ****************************

import path = require('path');

export const fsRoot = () => {
     return path.resolve(__dirname'../');
};