Skip to main content

Emi Headers class generator

In the context of http requests, there is always request and response headers, which is a key pair definition. Modern javascript standard is using Headers class, and Emi generates the header classes, by extending that class, and adding extra functions.

Example schema:

- name: accept-language
type: string
- name: authroization
type: string
- name: cache-time
type: int64

Would generate the following code:

/**
* SampleHeaders class
* Auto-generated from EmiAction
*/
export class SampleHeaders extends Headers {
/**
*
* @returns { string | null }
*/
getAcceptLanguage () {
return this.#getTyped('accept-language', 'string | null');
}
/**
*
* @param { string | null } value
*/
setAcceptLanguage (value) {
if (value !== null) {
this.set('accept-language', value);
}
return this;
}
/**
*
* @returns { string | null }
*/
getAuthroization () {
return this.#getTyped('authroization', 'string | null');
}
/**
*
* @param { string | null } value
*/
setAuthroization (value) {
if (value !== null) {
this.set('authroization', value);
}
return this;
}
/**
*
* @returns { number | null }
*/
getCacheTime () {
return this.#getTyped('cache-time', 'number | null');
}
/**
*
* @param { number | null } value
*/
setCacheTime (value) {
if (value !== null) {
this.set('cache-time', value);
}
return this;
}
// the getters generated by us would be casting types before returning.
// you still can use .get function to get the string value.
// eslint-disable-next-line no-unused-private-class-members
#getTyped(key, type) {
const val = this.get(key);
if (val == null) return null;
const t = type.toLowerCase();
if (t.includes('number')) return Number(val);
if (t.includes('bool')) return val === 'true';
return val; // string or any other fallback
}
/**
* @returns {Record<string, string>}
* Converts Headers to plain object
*/
toObject() {
return Object.fromEntries(this.entries());
}
}


function isPlausibleObject(v: any) { return false }