Utilities¶
In this guide we'll introduce a concept for service layer and how to implement it with TypeScript.
This is a general full stack concept which can be used for any type of software -- e.g. frontend, backend, Nginx's NJS or PostgreSQL's plv8.
What's utility class?¶
What makes a class utility class is the fact that it has no internal state except the values you provide to it as arguments.
E.g. it shouldn't use any other internal state which may change the result of the function. Hence, constants are fine to use, but global variables usually are not.
The second important part of the architecture is the context. You should place your functions based on a common context. Then you'll know where to look when you need it next time -- and so does your IDE. It also makes it easier to find a place to put your next new function.
Code Example¶
In its core a utility class is simply a collection of public functions in a common namespace which shares some context of purpose.
export class StringUtils {
public static strip (value: string) : string {
return value.replace(/ +/, "");
}
}
export default StringUtils;
...and use it:
import StringUtils from '../utils/StringUtils.ts';
console.log( StringUtils.strip('a b c') );
Filesystem hierarchy¶
You should place utils under the utils
and name them FooUtils.
It's also acceptable to place them in the services
as well.
Sometimes even beside the code that uses them, if that's the only place where it should be used.