Typescript undefined error produced for defined enum - node.js

In file defs.ts I define an enum and export it...
enum MyState {
state1 = 'state1'
state2 = 'state2'
... state5 = 'state5'
}
this gets exported to index.tsx of a Component and exported from there
export {
MyState,
...
}
It then gets imported into a file in another Component
import { MyState } from "../Component1"
const filterMap: { [key: string]: { title: string; filter: object } } = {
s1: { title: 's1', filter: { state: MyState.state1 } },
s2: { title: 's2', filter: { state: MyState.state2 } },
s2: { title: 's3', filter: { state_ne: [MyState.state3 ] } },
}
However on being run, an error gets generated
Uncaught TypeError: Cannot read properties of undefined (reading 'MyState')
WTF is going on?

This works for me
defs.ts
export enum MyState {
state1 = 'state1',
state2 = 'state2',
state5 = 'state5',
}
Component2.tsx
import { MyState } from './defs'
const filterMap: { [key: string]: { title: string; filter: object } } = {
s1: { title: 's1', filter: { state: MyState.state1 } },
s2: { title: 's2', filter: { state: MyState.state2 } },
s2: { title: 's3', filter: { state_ne: [MyState.state5 ] } },
}
If you need to export it from an intermediary you would do something like this.
Component1.tsx
export * from './defs'
I

Related

Customizer for mergeWith to not merge nested arrays

I need to write a customizer for mergeWith. I've used defaultsDeep before and it worked exactly the way I want it to, except that defaultsDeep also merge nested arrays. I have 2 objects.
const baseObject = {
firstElement: { data: undefined },
secondElement: {
name: 'Canada',
items: [
{ city: 'Toronto', code: 12334},
{ city: 'Vancouver ', code: 33245}
]
}
};
const defaultObject = {
firstElement: { data: '13.01.2018'},
secondElement: {
name: 'Bresil',
items: [
{ city: 'Rio', code: 67584},
{ city: 'Manaus ', code: 90845},
{ city: 'Salvador ', code: 36745}
]
}
};
and when I do defaultsDeep(baseObject, defaultObject)
I get:
{
firstElement: { data: '13.01.2018' },
secondElement: {
name: 'Canada',
items: [
{city: 'Toronto', code: 12334},
{city: 'Vancouver ', code: 33245},
{city: 'Salvador ', code: 36745}]
}
};
with mergeWith(mergeWith(baseObject, defaultObject, (ObjValue) => ObjValue))
I get:
{
firstElement: { data: undefined },
secondElement: {
name: 'Canada',
items: [
{city: 'Toronto', code: 12334},
{city: 'Vancouver ', code: 33245}]
}
};
Please help me to write customizer for mergeWith, I would be very appreciated 🙂
I expect :
{
firstElement: { data: '13.01.2018' },
secondElement: {
name: 'Canada',
items: [
{city: 'Toronto', code: 12334},
{city: 'Vancouver ', code: 33245}]
}
}
I found some resolving, and I understand that some lines no have sens, but it's work somehow :
const customizer = (objValue, key) => {
if (isArray(key) || objValue?.subItems) return objValue;
if (key) return;
return objValue;
};
The customizer function of _.mergeWith() should return the value that you want or undefined, if you would like _.mergeWith() continue merging nested objects:
const { isArray, isObject, isUndefined, mergeWith } = _;
const customizer = (a, b) => {
if(isArray(a)) return a;
return isObject(a) || isUndefined(a) ? undefined : a;
}
const baseObject = {"firstElement":{},"secondElement":{"name":"Canada","items":[{"city":"Toronto","code":12334},{"city":"Vancouver ","code":33245}]}};
const defaultObject = {"firstElement":{"data":"13.01.2018"},"secondElement":{"name":"Bresil","items":[{"city":"Rio","code":67584},{"city":"Manaus ","code":90845},{"city":"Salvador ","code":36745}]}};
const result = mergeWith(baseObject, defaultObject, customizer);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Array of objects with unique properties

Is there a way to declare an interface that one of the properties is an array of objects and inside those objects we have a property that acts similarly to a "primary key" in a database structure? To not allow repetition.
interface a {
myList: {
uniqueName: string;
}[]
}
const myAObject: a = {
myList: [
{
uniqueName: "bla-1"
},
{
uniqueName: "bla-2"
},
{
uniqueName: "bla-1" //shouldnt allow that
}
]
}
I've used a Record<> to achieve something similar:
interface myThings = {
a: string;
b: string;
c: string;
}
type item<T, K extends keyof T> = {
name: string;
value: T[K];
}
type items<T> = { [K in keyof T]-?: Record<K, item<T, K>> }[keyof T];
const myItems:items<myThings> = {
a: { //this uniqueness is enforced with Record<>
name: "some name"
},
b: {
name: "some name"
},
c: {
name: "some name"
}
}

Get local JSON data: The element has a type "any" implicitly

I have a project in Node JS with Typescript in which I am creating an API to get data from a local JSON file depending on the given variable.
This is my model.ts:
interface ListProductBatchModel {
resp: ResultMsg
}
interface ResultMsg {
name?: string,
price?: string,
error?: string
}
export { ListProductBatchModel, ResultMsg };
This is my properties JSON file:
{
"CT": {
"name": "box",
"price": "5,00"
},
"CC": {
"name": "car",
"price": "6,00"
}
}
This is my controller.ts:
import * as logger from 'winston';
import { Controller, Get, Response, Route, SuccessResponse, Tags } from 'tsoa';
import { ListProductBatchModel } from './models/listProduct.models';
import { ListProductBatchUtils } from './utils/listProductBatch.utils';
#Route('/list/product')
#Tags('list-product')
export class ListProductBatchController {
private listProductBatchUtils: ListProductBatchUtils;
constructor() {
this.listProductBatchUtils = new ListProductBatchUtils();
}
#Get('/{codProduct}')
#SuccessResponse(200, 'Success Response')
async listProductBatch(codProduct: string): Promise<ListProductBatchModel> {
try {
const listProductBatch = await this.listProductBatchUtils.getDataProduct(codProduct);
return Promise.resolve(listProductBatch as ListProductBatchModel);
} catch (error) {
logger.info(JSON.stringify(error));
return Promise.reject(error);
}
}
}
This is my utils.ts:
import * as logger from 'winston';
import * as getProperty from '../json/product.json';
import { ListProductBatchModel, ResultMsg } from '../models/listProduct.models';
export class ListProductBatchUtils {
public async getDataProduct(codProduct: string): Promise<ListProductBatchModel> {
try {
let result: ResultMsg;
if (getProperty[codProduct.toUpperCase()]) {
result = {
name: getProperty[codProduct.toUpperCase()].name,
price: getProperty[codProduct.toUpperCase()].price
}
}else {
result = {
error: "ERROR"
}
}
logger.info('start')
return Promise.resolve({ resp: result });
} catch (error) {
logger.info(JSON.stringify(error));
return Promise.reject(error);
}
}
}
This is the error I get in getProperty [codProduct.toUpperCase ()]:
The element has a type "any" implicitly because the expression of type "string" cannot be used to index the type "{CT: {name: string; price: string;}; CC: {name: string; price : string;};} ".
No index signature was found with a parameter of type "string" in type "{CT: {name: string; price: string;}; CC: {name: string; price: string;};}".
My problem: I don't understand how the error is generated, what I want is to take the name and price properties that match the codProduct variable. Why can this happen? What am I doing wrong and how can I solve it?
Right now, codProduct is a string. When you're accessing getProduct via its subscript [], TypeScript expects you to use an index of getProduct (which, in this case is either "CT" or "CC").
You can satisfy the TypeScript compiler by casting your string as a keyof getProperty's type. Note that this will work at compile time, but will not guarantee that it is in fact a key of getProperty at runtime. But, since you're doing boolean checks already, that seems like it will be okay in your case.
Here's a simplified example:
const getProperty = {
"CT": {
"name": "box",
"price": "5,00"
},
"CC": {
"name": "car",
"price": "6,00"
}
};
type GetPropertyType = typeof getProperty;
function myFunc(input: string) {
const result = getProperty[input.toUpperCase() as keyof GetPropertyType].name;
}

Get child component reference in parent component

I am new to Angular and stuck on an issue. Anyone can help me to figure out that what I am doing wrong in parent component. I am not able to get the child component reference in parent. I already followed following reference but not succeeded.
Angular 2 #ViewChild annotation returns undefined
https://expertcodeblog.wordpress.com/2018/01/12/angular-resolve-error-viewchild-annotation-returns-undefined/
Parent:
import { Component, OnInit, OnDestroy, ViewChild, HostListener, AfterViewInit, ViewChildren, QueryList } from '#angular/core';
import { Router, NavigationEnd, NavigationStart } from '#angular/router';
import { NavItem, NavItemType } from '../../md/md.module';
import { Subscription } from 'rxjs/Subscription';
import { Location, LocationStrategy, PathLocationStrategy, PopStateEvent } from '#angular/common';
import 'rxjs/add/operator/filter';
import { NavbarComponent } from '../../shared/navbar/navbar.component';
import PerfectScrollbar from 'perfect-scrollbar';
import { ChatService } from 'app/services/chat.service';
import swal from 'sweetalert2';
import { JitsiService } from 'app/services/jitsi.service';
import { UserService } from 'app/services/user.service';
import { ConferenceStudentComponent } from 'app/conference-student/conference-student.component';
declare const $: any;
#Component({
selector: 'app-layout',
templateUrl: './admin-layout.component.html'
})
export class AdminLayoutComponent implements OnInit, AfterViewInit {
public navItems: NavItem[];
private _router: Subscription;
private lastPoppedUrl: string;
private yScrollStack: number[] = [];
url: string;
location: Location;
#ViewChild('sidebar') sidebar: any;
#ViewChild(NavbarComponent) navbar: NavbarComponent;
#ViewChildren(ConferenceStudentComponent) stuConf: QueryList<ConferenceStudentComponent>;
constructor( private router: Router, location: Location,
private chatService: ChatService,
private jitsiService: JitsiService,
private userService: UserService
) {
this.location = location;
this.chatService.callVisibilityChange
.subscribe(callFrom => {
console.log('admin layout call from', callFrom);
if (callFrom) {
this.userService.getLoggedUserDetail()
.subscribe(loggedUser => {
if (!loggedUser) {
console.log(`Invalid token, logged user data not fetched`);
return false;
}
this.userService.getUser(callFrom['fromUser'])
.subscribe(otherUser => {
swal({
title: `${otherUser['fullName']} is calling`,
text: `Click on accept to join session`,
type: `info`,
showCancelButton: true,
cancelButtonColor: `#d33`,
cancelButtonText: `reject`,
confirmButtonColor: `#3085d6`,
confirmButtonText: `accept`
}).then((result) => {
if (result.value) {
const jitsiSessionData = {
loggedUser,
otherUser,
roomName: callFrom['roomName']
}
this.router.navigateByUrl(`/conference-student/${otherUser['_id']}`);
window.setTimeout(() => this.jitsiService.joinSession(jitsiSessionData), 10000);
} else {
console.log('user select rejected');
this.chatService.jitsiCallReject(otherUser._id, loggedUser._id, callFrom['roomName']);
}
})
});
});
}
});
}
ngOnInit() {
const elemMainPanel = <HTMLElement>document.querySelector('.main-panel');
const elemSidebar = <HTMLElement>document.querySelector('.sidebar .sidebar-wrapper');
this.location.subscribe((ev:PopStateEvent) => {
this.lastPoppedUrl = ev.url;
});
this.router.events.subscribe((event:any) => {
if (event instanceof NavigationStart) {
if (event.url != this.lastPoppedUrl)
this.yScrollStack.push(window.scrollY);
} else if (event instanceof NavigationEnd) {
if (event.url == this.lastPoppedUrl) {
this.lastPoppedUrl = undefined;
window.scrollTo(0, this.yScrollStack.pop());
}
else
window.scrollTo(0, 0);
}
});
this._router = this.router.events.filter(event => event instanceof NavigationEnd).subscribe((event: NavigationEnd) => {
elemMainPanel.scrollTop = 0;
elemSidebar.scrollTop = 0;
});
const html = document.getElementsByTagName('html')[0];
if (window.matchMedia(`(min-width: 960px)`).matches && !this.isMac()) {
let ps = new PerfectScrollbar(elemMainPanel);
ps = new PerfectScrollbar(elemSidebar);
html.classList.add('perfect-scrollbar-on');
}
else {
html.classList.add('perfect-scrollbar-off');
}
this._router = this.router.events.filter(event => event instanceof NavigationEnd).subscribe((event: NavigationEnd) => {
this.navbar.sidebarClose();
});
this.navItems = [
{ type: NavItemType.NavbarLeft, title: 'Dashboard', iconClass: 'fa fa-dashboard' },
{
type: NavItemType.NavbarRight,
title: '',
iconClass: 'fa fa-bell-o',
numNotifications: 5,
dropdownItems: [
{ title: 'Notification 1' },
{ title: 'Notification 2' },
{ title: 'Notification 3' },
{ title: 'Notification 4' },
{ title: 'Another Notification' }
]
},
{
type: NavItemType.NavbarRight,
title: '',
iconClass: 'fa fa-list',
dropdownItems: [
{ iconClass: 'pe-7s-mail', title: 'Messages' },
{ iconClass: 'pe-7s-help1', title: 'Help Center' },
{ iconClass: 'pe-7s-tools', title: 'Settings' },
'separator',
{ iconClass: 'pe-7s-lock', title: 'Lock Screen' },
{ iconClass: 'pe-7s-close-circle', title: 'Log Out' }
]
},
{ type: NavItemType.NavbarLeft, title: 'Search', iconClass: 'fa fa-search' },
{ type: NavItemType.NavbarLeft, title: 'Account' },
{
type: NavItemType.NavbarLeft,
title: 'Dropdown',
dropdownItems: [
{ title: 'Action' },
{ title: 'Another action' },
{ title: 'Something' },
{ title: 'Another action' },
{ title: 'Something' },
'separator',
{ title: 'Separated link' },
]
},
{ type: NavItemType.NavbarLeft, title: 'Log out' }
];
}
ngAfterViewInit() {
this.runOnRouteChange();
this.stuConf.changes.subscribe((comp: QueryList<ConferenceStudentComponent>) => {
console.log(`student component`, comp);
})
}
public isMap() {
if (this.location.prepareExternalUrl(this.location.path()) === '/maps/fullscreen') {
return true;
} else {
return false;
}
}
runOnRouteChange(): void {
if (window.matchMedia(`(min-width: 960px)`).matches && !this.isMac()) {
const elemSidebar = <HTMLElement>document.querySelector('.sidebar .sidebar-wrapper');
const elemMainPanel = <HTMLElement>document.querySelector('.main-panel');
let ps = new PerfectScrollbar(elemMainPanel);
ps = new PerfectScrollbar(elemSidebar);
ps.update();
}
}
isMac(): boolean {
let bool = false;
if (navigator.platform.toUpperCase().indexOf('MAC') >= 0 || navigator.platform.toUpperCase().indexOf('IPAD') >= 0) {
bool = true;
}
return bool;
}
}
Child:
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute, ParamMap } from '#angular/router';
import '../../vendor/jitsi/external_api.js';
import { JitsiService } from 'app/services/jitsi.service.js';
import { UserService, UserSchema } from 'app/services/user.service.js';
import swal from 'sweetalert2';
declare var JitsiMeetExternalAPI: any;
declare const $: any;
#Component({
selector: "app-conference-student-cmp",
templateUrl: "conference-student.component.html"
})
export class ConferenceStudentComponent implements OnInit {
roomName: string;
tutor: UserSchema
student: UserSchema;
domain: string;
options: any;
api: any;
hasActiveRoom: boolean;
tutorId: string;
conferenceJoined: boolean;
constructor(
private route: ActivatedRoute,
private jitsiService: JitsiService,
private userService: UserService
) { }
ngOnInit() {
this.conferenceJoined = false;
// this.domain = "jitsi.liquidclouds.in";
this.domain = 'meet.jit.si';
this.route.paramMap.subscribe((params: ParamMap) => this.tutorId = params.get('id'));
this.userService
.getLoggedUserDetail()
.subscribe(student => {
// store student
this.student = student;
this.userService.getUser(this.tutorId)
.subscribe((tutor: UserSchema) => {
// store tutor
this.tutor = tutor;
const obj = { tutorId: this.tutor['_id'], studentId: this.student['_id'] };
this.jitsiService.getActiveRoomForStudent(obj).subscribe(resp => {
if (resp && resp['result'] && resp['result']['roomName']) {
this.hasActiveRoom = true;
this.roomName = resp['result']['roomName'];
}
});
});
});
}
joinSession() {
this.options = {
roomName: this.roomName,
width: 800,
height: 500,
parentNode: document.querySelector('#jitsiVideo'),
configOverwrite: {},
interfaceConfigOverwrite: {
// filmStripOnly: true,
TOOLBAR_BUTTONS: [
'microphone', 'camera', 'closedcaptions', 'desktop', 'fullscreen',
'hangup', 'profile', 'chat', 'recording'
],
}
};
this.api = new JitsiMeetExternalAPI(this.domain, this.options);
this.api.executeCommand('displayName', this.student['fullName']);
this.api.addEventListeners({
readyToClose: this.unload,
participantLeft: this.handleParticipantLeft,
participantJoined: this.handleParticipantJoined,
videoConferenceJoined: this.handleVideoConferenceJoined,
videoConferenceLeft: this.handleVideoConferenceLeft
});
this.conferenceJoined = true;
}
unload = () => {
if (this.api instanceof JitsiMeetExternalAPI) {
this.api.dispose();
}
$('#jitsiVideo').html('');
this.conferenceJoined = false;
this.hasActiveRoom = false;
}
handleParticipantLeft = (arg) => {
this.jitsiService.getJitsiDetailByParticipantId(arg.id)
.subscribe(async roomDetail => {
if (!roomDetail) {
console.log(`No room is joined by the participant id: ${arg.id}`);
return false;
} else {
const participantDetail = roomDetail['participants'].filter(el => el.jitsiParticipantId === arg.id)[0];
if (participantDetail) {
switch (participantDetail.type) {
case 'manager':
console.log('Left participant is manager');
break;
case 'supervisor':
console.log('Left participant is supervisor');
break;
case 'student':
console.log('Left participant is student');
break;
case 'tutor':
console.log('Left participant is tutor');
this.api.dispose();
this.conferenceJoined = false;
this.hasActiveRoom = false;
alert('Tutor left the session.');
break;
default:
console.log('Left participant is not a valid type');
break;
}
}
}
});
}
handleParticipantJoined = (arg) => {
console.log('participant joined: ', arg, this.api);
}
handleVideoConferenceJoined = (arg) => {
const obj = {
participantId: arg.id,
roomName: arg.roomName,
tutorId: this.tutor['_id'],
studentId: this.student['_id'],
studentJoined: 'yes',
joineeType: 'student',
}
// save new room
this.jitsiService.updateJitsiRoomForStudent(obj);
}
handleVideoConferenceLeft = (arg) => {
}
}
admin-layout.componet.html
<div class="wrapper">
<div class="sidebar" data-color="rose" data-background-color="white" data-image="./assets/img/sidebar-1.jpg">
<app-sidebar-cmp></app-sidebar-cmp>
<div class="sidebar-background" style="background-image: url(assets/img/sidebar-1.jpg)"></div>
</div>
<div class="main-panel">
<router-outlet></router-outlet>
<div *ngIf="!isMap()">
<app-footer-cmp></app-footer-cmp>
</div>
</div>
<app-fixedplugin></app-fixedplugin>
</div>

How to create schema using model interfaces with type script mongoose

In my project using technologies are Nodejs,Mongoose, Express,Type script
I want to create below-mentioned JSON format collection in Mongodb
{
"emp_id": "001",
"login_id": "venue#abc.com",
"password": "venue123",
"role_id": 6,
"role_name": "TechLead",
"emp_ext": 456;
"leave_details": {
"leave_transactions": [
{
"leave_from_date": "14-10-2016",
"leave_from_part": "noon",
"leave_to_date": "16-10-2016",
"leave_to_part": "full",
"total_no_of_days": 2.5,
"leave_approved_by_id": "87",
"leave_approved_date": "14-10-2016",
"leave_applied_on": "13-10-2016",
"leave_status": "approved",
"leave_type": "EL",
"leave_desc": "going to hometown"
},
{
"leave_from_date": "18-11-2016",
"leave_from_part": "full",
"leave_to_date": "19-11-2016",
"leave_to_part": "full",
"total_no_of_days": 2,
"leave_approved_by_id": "115",
"leave_approved_date": "17-11-2016",
"leave_applied_on": "17-11-2016",
"leave_status": "approved",
"leave_type": "CL",
"leave_desc": "not feeling well",
"rejected_reason":""
}
]
}
}
To create above structure created below model interfaces and classes
import mongoose = require("mongoose");
import IJoiningDetailsModel = require('./JoiningDetailsModel');
import ILeaveDetailsModel = require('./LeaveDetailsModel');
interface EmployeeMasterModel extends mongoose.Document {
emp_id: number;
login_id: string;
name: string;
password: string;
role_id: number;
role_name: string;
emp_ext: number;
leave_details: ILeaveDetailsModel;
}
export = EmployeeMasterModel;
import IEmployeeMasterModel = require('./interfaces/EmployeeMasterModel');
import JoiningDetailsModel = require('./JoiningDetailsModel');
import IJoiningDetailsModel = require('./interfaces/JoiningDetailsModel');
import ILeaveDetailsModel = require('./interfaces/LeaveDetailsModel');
class EmployeeMasterModel {
private employeeModel: IEmployeeMasterModel;
constructor(employeeModel: IEmployeeMasterModel) {
this.employeeModel = employeeModel;
}
get name (): string {
return this.employeeModel.name;
}
get email (): string {
return this.employeeModel.login_id;
}
get password (): string {
return this.employeeModel.password;
}
get leave_details (): ILeaveDetailsModel {
return this.employeeModel.leave_details;
}
}
Object.seal(EmployeeMasterModel);
export = EmployeeMasterModel;
import mongoose = require("mongoose");
import mongoose = require("mongoose");
import ILeaveTransactionModel = require('./LeaveTransactionModel');
interface LeaveDetailsModel extends mongoose.Document {
leaveTransactionModel: ILeaveTransactionModel;
}
export = LeaveDetailsModel;
import ILeaveDetailsModel = require('./interfaces/LeaveDetailsModel');
import ILeaveTransactionModel = require('./interfaces/LeaveTransactionModel');
class LeaveDetailsModel {
private leaveDetailsModel: ILeaveDetailsModel;
constructor(leaveDetailsModel: ILeaveDetailsModel) {
this.leaveDetailsModel = leaveDetailsModel;
}
get leaveTransactionModel (): ILeaveTransactionModel {
return this.leaveDetailsModel.leaveTransactionModel;
}
}
Object.seal(LeaveDetailsModel);
export = LeaveDetailsModel;
import mongoose = require("mongoose");
interface LeaveTransactionModel extends mongoose.Document {
leave_from_date:Date;
leave_from_part : string;
leave_to_date : Date;
leave_to_part :string;
total_no_of_days :number;
leave_type :string;
leave_desc:string;
rejected_reason:string;
leave_approved_by_id:number;
leave_approved_date:Date;
leave_applied_on:Date;
leave_status:string;
}
export = LeaveTransactionModel;
import ILeaveTransactionModel = require('./interfaces/LeaveTransactionModel');
class LeaveTransactionModel {
private leaveTransactionModel: ILeaveTransactionModel;
constructor(leaveTransactionModel: ILeaveTransactionModel) {
this.leaveTransactionModel = leaveTransactionModel;
}
get leave_from_date (): Date {
return this.leaveTransactionModel.leave_from_date;
}
set leave_from_date(leave_from_date : Date){
this.leaveTransactionModel.leave_from_date = leave_from_date;
}
get leave_from_part (): string {
return this.leaveTransactionModel.leave_from_part;
}
get leave_to_date (): Date {
return this.leaveTransactionModel.leave_to_date;
}
get leave_to_part (): string {
return this.leaveTransactionModel.leave_to_part;
}
get total_no_of_days () : number{
return this.leaveTransactionModel.total_no_of_days;
}
get leave_type (): string {
return this.leaveTransactionModel.leave_type;
}
get leave_desc (): string {
return this.leaveTransactionModel.leave_desc;
}
get rejected_reason (): string {
return this.leaveTransactionModel.rejected_reason;
}
get leave_status (): string {
return this.leaveTransactionModel.leave_status;
}
get leave_approved_by_id () : number{
return this.leaveTransactionModel.leave_approved_by_id;
}
get leave_approved_date (): Date {
return this.leaveTransactionModel.leave_approved_date;
}
get leave_applied_on (): Date {
return this.leaveTransactionModel.leave_applied_on;
}
}
Object.seal(LeaveTransactionModel);
export = LeaveTransactionModel;
Schema class
import DataAccess = require('../DataAccess');
import IEmployeeMasterModel = require("./../../model/interfaces/EmployeeMasterModel");
var mongoose = DataAccess.mongooseInstance;
var mongooseConnection = DataAccess.mongooseConnection;
class EmployeeMasterSchema {
static get schema () {
// Employee leave transactions(request/approve/cancel) schema declaration
var LeaveTransactionsSchema = mongoose.Schema({
leave_from_date: {
type: Date,
required: false
},
leave_from_part: {
type: String
},
leave_to_date: {
type: Date,
required: false
},
leave_to_part: {
type: String
},
total_no_of_days: {
type: String,
required: false
},
leave_type: {
type: String,
required: false
},
leave_desc: {
type: String,
required: false
},
rejected_reason: {
type: String
},
leave_approved_by_id: {
type: Number,
required: false
},
leave_approved_date: {
type: Date
},
leave_applied_on: {
type:Date,
required: false
},
leave_status: {
type: String,
required: false
}
});
// Employee leave details schema declaration
var LeaveDetailsSchema = mongoose.Schema({
leave_transactions: {
type: [ LeaveTransactionsSchema ]
}
});
// Employee master schema declaration
var schema = mongoose.Schema({
emp_id : {
type: Number,
required: false
},
login_id: {
type: String,
required: false
},
password: {
type: String,
required: false
},
role_id: {
type: Number
},
role_name: {
type: String
},
emp_ext: {
type: Number
},
leave_details: {
type: [ LeaveDetailsSchema ]
}
});
return schema;
}
}
var schema = mongooseConnection.model<IEmployeeMasterModel>("employee", EmployeeMasterSchema.schema);
export = schema;
when i get request below method gets called ,for testing purpose setting data to ILeaveTransactionModel but when i try to set the ILeaveTransactionModel to not working ... How to set ILeaveTransactionModel into ILeaveDetailsModel.thanks in advance
import express = require("express");
import LeaveTraBusiness = require("./../app/business/LeaveTraBusiness");
import IBaseController = require("./BaseController");
import LeaveTransactionModel = require("./../app/model/LeaveTransactionModel");
import ILeaveDetailsModel = require("./../app/model/interfaces/LeaveDetailsModel");
import ILeaveTransactionModel = require("./../app/model/interfaces/LeaveTransactionModel");
// tslint:disable-next-line:one-line
export class LeaveTraController implements IBaseController<LeaveTraBusiness>{
leaveTra :any;
create(req: express.Request, res: express.Response): void {
try {
console.log(req.body.leave_desc);
this.leaveTra = <ILeaveTransactionModel>{
leave_from_date:new Date(),
leave_from_part : "Full",
leave_to_date : new Date(),
leave_to_part :"half",
total_no_of_days :5,
leave_type :"SL",
leave_desc:"No comme",
rejected_reason:"No comme",
leave_approved_by_id:121,
leave_approved_date:new Date(),
leave_applied_on:new Date(),
leave_status:"Active"
};
console.log(JSON.stringify(this.leaveTra));
let leaveTraBusiness = new LeaveTraBusiness();
//Here i want to set leaveTra to ILeaveDetailsModel
let leaveDetailsModel : <ILeaveDetailsModel>{leaveTra};
leaveTraBusiness.create(leaveDetailsModel, (error, result) => {
if (error)
res.send({"error": "error"});
else
res.send(result);
});
}
catch (e) {
console.log(e);
res.send({"error": "error in your request"});
}
}
}
Sorry, I did mistake in setting "leaveTra" to , below code solved my problem
let leaveDetailsModel = {
leaveTransactionModel: leaveTra
};

Resources