TypeScript: Elegant way to write single line helper functions - node.js

I have a simple helper / util sort of class where there are some one/two liner utilities which I am planning to use across the code.
I am using Nest Js/Node Js with TypeScript.
I am just thinking how better, elegantly I can write these helper methods, preferably in a one-liner sort of .. sweet and nice.
My attempt so far
import { Injectable } from '#nestjs/common';
#Injectable()
export class HelperOperations {
static zones(region: string): string[] {
return region.split(',', 2);
}
static instanceNames(name: string): string[] {
return [`${name}-vm1`, `${name}-vm2`];
}
static mediatorName(name): string {
return `${name}-mediator`;
}
static mediatorZone(region: string): string {
return region.split(",").pop();
}
static zoneNamePair(name, region): [string, string][] {
const zoneNamePair: [string, string][] = [];
const zones = HelperOperations.zones(region);
HelperOperations.instanceNames(name).map((instName, i) => zoneNamePair.push([instName, zones[i]]));
return zoneNamePair;
}
}
Expected Outcome:
Better, elegant way to rewrite this class for betterment, of course strongly typed.

Generally (dunno about Nest) this is done with exports or with namespaces
export const zones = (region: string) => region.split(',', 2);
export namespace z1 {
export const zones = (region: string) => region.split(',', 2);
}
////////////
import {zones} from './z'
import * az z0 from './z'
import {z1} from './z'
zones('a')
z0.zones('a')
z1.zones('a')

Related

Get filename of derived class from base class in typescript running on node.js?

I'm looking for a way to get the filename of a derived class from a base class in typescript running on node.js. An example of this would be:
Foo.ts
export abstract class Foo {
constructor() { }
name() { return (__filename); }
print() { console.log(this.name()); }
}
Bar.ts
import { Foo } from './Foo';
export class Bar extends Foo {
constructor() { super(); }
}
main.ts
import { Bar } from './Bar';
let bar = new Bar();
bar.print(); // should yield the location of Bar.ts
Due to the number of files involved and just cleanliness I'd like this to be confined to the Foo class rather than having an override of the name() function in each derived class.
I was able to sort-of solve this with the code:
private getDerivedFilePath(): string {
let errorStack: string[] = new Error().stack.split('\n');
let ret: string = __filename;
let baseClass: any = ThreadPoolThreadBase;
for (let i: number = 3; i < errorStack.length; i++) {
let filename: string = errorStack[i].slice(
errorStack[i].lastIndexOf('(') + 1,
Math.max(errorStack[i].lastIndexOf('.js'), errorStack[i].lastIndexOf('.ts')) + 3
);
let other: any = require(filename);
if (other.__proto__ === baseClass) {
ret = filename;
baseClass = other;
} else {
break;
}
}
return (ret || '');
}
Added to Foo, which will work when called from the constructor to set a private _filename property, for inheritance chains beyond the example above so long as the files are structured with a default export of the class being used. There may also be a caveat that if a base class from which a derived object is inheriting directly is initialized as a separate instance within the constructor of any member of the inheritance chain it could get confused and jump to another independent derived class - so it's a bit of a hacky work-around and I'd be interested if someone comes up with something better, but wanted to post this in case someone stumbles across this question and it works for them.
You can use require.cache to get all cached NodeModule objects and filter it to find your module.
https://nodejs.org/api/modules.html#requirecache
class ClassA {
public static getFilePath():string{
const nodeModule = this.getNodeModule();
return (nodeModule) ? nodeModule.filename : "";
}
public static getNodeModule(): NodeModule | undefined{
const nodeModule = Object.values(require.cache)
.filter((chl) => chl?.children.includes(module))
.filter((mn)=> mn?.filename.includes(this.name))
.shift();
return nodeModule;
}
}
class ClassB extends ClassA {
constructor(){}
}
const pathA = ClassA.getFilePath(); //Must return the absolute path of ClassA
const pathB = ClassB.getFilePath(); //Must return the absolute path of ClassB

This expression is not constructable. Type 'xxxx' has no construct signatures

I have a mistake that I can't understand what I'm doing wrong. I am following the instructions set out at https://docs.nestjs.com/techniques/mongodb. The difference is that I created interfaces to build different strategies for implementing a service (and for that I am making a wrapper in Model ).
import { Inject, Injectable } from "#nestjs/common";
import { Model } from "mongoose";
import { Documents } from "src/domain/schemas/documents.schema";
interface IDocumentRepository {
save();
}
interface IDocumentRepositoryFactory {
new(doc?: any): IDocumentRepository;
}
export function createIDocumentRepository(ctor: IDocumentRepositoryFactory, doc?: any): IDocumentRepository {
return new ctor(doc);
}
#Injectable()
export class DocumentRepository implements IDocumentRepository {
constructor(
private doc?: Documents,
#Inject()
private repository?: Model<Documents>
) {}
/* others fields and methods */
save() {
this.doc.save()
}
}
In others code points I call:
someMethod(repository: DocumentRepository) {
/* others codes */
const mdoc = new this.repository(mongoModelDoc); // <<<<---- error
mdoc.save();
/* others codes */
}
It is causing the following error:
This expression is not constructable. Type 'DocumentRepository' has no construct signatures.
return new this.repository(document)
What is wrong and how to resolve to meet this implementation?

NestJS: dynamically call various services for batch processing

I have some Service classes as follows:
//Cat Service:
import { Injectable } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { Repository, getManager } from 'typeorm';
import { CatRepo } from '../tables/catrepo.entity';
import { CatInterface } from './cat.interface';
#Injectable()
export class CatService {
constructor(
#InjectRepository(CatRepo)
private catRepo: Repository<CatRepo>,
) {}
async customFindAll(offset:number, limit: number): Promise<CatRepo[]> {
const entityManager = getManager();
const catRows = await entityManager.query(
`
SELECT * FROM CATREPO
${offset ? ` OFFSET ${offset} ROWS ` : ''}
${limit ? `FETCH NEXT ${limit} ROWS ONLY` : ''}
`,
);
return catRows;
}
formResponse(cats: CatRepo[]): CatInterface[] {
const catsResults: CatInterface[] = [];
.
//form cat response etc.
.
//then return
return catsResults;
}
}
//Pet Service:
import { Injectable } from '#nestjs/common';
import { getManager } from 'typeorm';
import { PetInterface } from './pet.interface';
#Injectable()
export class PetService {
async customFindAll(offset:number, limit: number) {
const entityManager = getManager();
const petRows = await entityManager.query(
`
JOIN ON TABLES......
${offset ? ` OFFSET ${offset} ROWS ` : ''}
${limit ? `FETCH NEXT ${limit} ROWS ONLY` : ''}
`,
);
//returns list of objects
return petRows;
}
formResponse(pets): PetInteface[] {
const petsResults: PetInteface[] = [];
.
. //form pet response etc.
.
//then return
return petsResults;
}
}
I am running a cron BatchService that uses these two services subsequently saving the data into respective batch files.
I'm calling CatService and PetService from the BatchService as follows:
/Start the Batch job for Cats.
if(resource === "Cat") {
//Call Cat Service
result = await this.catService.findAllWithOffest(startFrom, fetchRows);
finalResult = this.catService.formResponse(result);
}
//Start the batch job for Pets.
if(resource === "Pet") {
//Call Pet Service
result = await this.petService.findAllWithOffest(startFrom, fetchRows);
finalResult = this.petService.formResponse(result);
}
However, instead of the above I want to use these Services dynamically.
In order to achieve the CatService and PetService now extends AbstractService...
export abstract class AbstractService {
public batchForResource(startFrom, fetchRows) {}
}
//The new CatService is as follows:
export class CatService extends AbstractService{
constructor(
#InjectRepository(CatRepo)
private catRepo: Repository<CatRepo>,
) {}
.
.
.
}
//the new PetService is:
export class PetService extends AbstractService{
constructor(
) {super()}
.
.
.
}
//the BatchService...
public getService(context: string) : AbstractService {
switch(context) {
case 'Cat': return new CatService();
case 'Pet': return new PetService();
default: throw new Error(`No service found for: "${context}"`);
}
}
However in the CatService I'm getting the a compilation error...(Expected 1 Argument but got 0). What should be the argument passed in the CatService.
Also, the larger question is if this can be achieved by using NestJS useValue/useFactory...If so how to do it?
You can probably use useFactory to dynamically retrieve your dependencies but there are some gotcha's.
You must make the lifecycle of your services transient, since NestJS dependencies are registered as singletons by default. If not, you would get the same first service injected each time, regardless of the context of subsequent calls.
Your context must come from another injected dependency - ExecutionContext, Request or something similarly dynamic, or something you register yourself.
Alternative
As an alternative, you can implement the "servicelocator/factory" pattern. You're already halfway there with your BatchService. Instead of your service creating instances of the CatService and PetService, you have it injected and just return the injected services depending on the context. Like so:
#Injectable()
export class BatchService {
constructor(
private readonly catService: CatService,
private readonly petService: PetService
)
public getService(context: string) : AbstractService {
switch(context) {
case 'Cat': return this.catService;
case 'Pet': return this.petService;
default: throw new Error(`No service found for: "${context}"`);
}
}
}
The alternative is more flexible than using useFactory, since your context is not limited to what is available in the DI container. On the negative side, it does expose some (usually unwanted) infrastructure details to the calling code, but that's the tradeoff you'll have to make.

Instantiate object after promisified import

I am struggling to instantiate object from dynamically imported classes. Basically I have some plugins which kinda look like this:
export interface IPlugin {
compile(logEvent: LogEventInfo): string;
}
export class DatePlugin implements IPlugin {
public compile(logEvent: LogEventInfo): string {
const date: Date = new Date();
return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
}
}
In another file I want to dynamically crawl a folder, load all source files and instantiate them. I saw that import(...).then() can return a loaded object however in my case it returns the class and my object creation starts looking very ugly:
public async loadPlugins(): Promise<void> {
// ...
await Promise.all(pluginFiles.map(async (pluginFile: string): Promise<void> => {
const pluginFilePath: string = path.join(pluginsFolder, pluginFile);
import(pluginFilePath).then((plugin: any): void => {
const obj: IPlugin = (new plugin[Object.keys(plugin)[0]]() as IPlugin;
// ...
});
}));
}
Isn't there any better way to instantiate all those classes when loading them?
import() promises aren't chained, this is a mistake similar to this case that may result in problems with error handling and race conditions.
map shares a common potential problem with this case. It's used only to provide promises to wait for them, but not actual values. Since the purpose of async function call is to get class instance, it's reasonable to map pluginFile input to obj output value if it's supposed to be stored then - or compile result if it isn't:
public async loadPlugins(): Promise<...> {
const plugins = await Promise.all(pluginFiles.map(async (pluginFile: string): Promise<IPlugin> => {
const pluginFilePath: string = path.join(pluginsFolder, pluginFile);
const pluginExports = await import(pluginFilePath);
// preferably pluginExports.default export to not rely on keys order
const Plugin: { new(): IPlugin } = Object.values(pluginExports)[0];
return new Plugin();
}));
...
}
The only real benefit that import provides here is that it's future-proof, it can seamlessly be used natively in Node.js with third-party ES modules (.mjs) files. Since TypeScript is used any way and uses require for ES module imports under the hood, it may be reasonable to discard asynchronous routine and use require synchronously instead of import for dynamic imports:
public loadPlugins(): <...> {
const plugins = pluginFiles.map((pluginFile: string): IPlugin => {
const pluginFilePath: string = path.join(pluginsFolder, pluginFile);
const pluginExports = require(pluginFilePath);
// preferably pluginExports.default export to not rely on keys order
const Plugin: { new(): IPlugin } = Object.values(pluginExports)[0];
return new Plugin();
}));
...
}

Externalize strings and use a formatter to substitute variables into string

I'd like to externalize some strings but still use some form of string substitution.
In some of my node based projects I've used:
var format = require('string-format');
format(Constants.COUNTRY_WEATHER_ENDPOINT, {
country: country
})
However In Typescript, I've been trying something like this ..
Error:
Cannot find name 'country'.at line 18 col 66 in repo/src/app/constants.ts
Constants.ts
export class Constants {
public static COUNTRY_WEATHER_ENDPOINT = `/api/country/${country}/weather`;
}
TestService.ts
import { Constants } from './constants';
export class TestService {
constructor(private $http) { }
public getWeather(country) {
let url = Constants.COUNTRY_WEATHER_ENDPOINT;
return this.$http.get(
url,
.then(response => response);
}
}
TestService.$inject = ['$http'];
Use arrow functions:
export const Constants: { readonly [name: string]: (key: string) => string } = {
countryWeatherEndpoint: country => `/api/country/${country}/weather`
}
Then do:
import { Constants } from "./constants";
// ...
const url = Constants.countryWeatherEndpoint(country);
// use your url
String interpolation in Typescript needs your variable country to exist when class is loaded. If you want to format later the constant string, you have to use normal quotes (single or double) and call format in your service.

Resources