trying to add jsdocs to dynamically generated functions

270 Views Asked by At

I have a class that generates simple CRUD functions of a given table. I have the jsdoc documentation working the way I want it (mostly for autofill purposes) when I init it once. ie const providerService = new CrudFunctions('provider'). However I may be adding more tables in the future, and I'll be wanting to generate all the tables in a loop so I don't have to repeat a bunch of code. Here's what I have so far to generate all the functions so far:

const generateTableFunctions = (tableArray) => {
  const tableFunctions = {};

  tableArray.forEach((table) => {
    tableFunctions[table] = new CrudFunctions(table);
  });
  return tableFunctions;
};

const foo = generateTableFunctions([
  'service',
  'payment',
  'certification',
  'provider',
  'provider_certifcation',
  'provider_payment',
  'provider_service'
]);

What I would really like is for "foo." to suggest a table name, but if nothing else I would really like "foo.provider." to suggest getAll, getOne, and add. I've tried making the generator function a jsdoc template, I've tried using typedef but no matter what I don't get any suggestions for foo. Here's the class:

/** Class representing crud functions of a given table */
class CrudFunctions {
  /**
   * @param {string} table - the name of the table from the database
   */
  constructor(table) {
    this.table = table;
  }
  /**
   * get all items from the table
   *
   * @returns {Object} all rows from table
   */
  async getAll() {
    const { rows } = await handleQuery(`SELECT * FROM ${this.table}`);
    return rows;
  }

  /**
   * gets a single item from the table
   *
   * @param {number} id - the unique id of the item we're looking up
   * @returns {Object} the item from the table
   */
  async getOne(id) {
    const { rows } = await handleQuery(
      `SELECT * FROM ${this.table} WHERE ID=${id}`
    );
    return rows;
  }

  /**
   *
   * @param {object} item - an item to be added to the table. all keys should be valid in the database already
   * @returns confirmation that the item got added
   */
  async add(item) {
    const res = await handleQuery(
      buildQuery(`INSERT INTO ${this.table}`, Object.keys(item)),
      Object.values(item)
    );
    return res;
  }
}

1

There are 1 best solutions below

0
lepsch On

The following would do the trick:

/**
 * @template {string} T
 * @param {T[]} tableArray
 */
const generateTableFunctions = (tableArray) => {
  const tableFunctions = /** @type {Record<T, CrudFunctions>} */({});

  tableArray.forEach((table) => {
    tableFunctions[table] = new CrudFunctions(table);
  });
  return tableFunctions;
};


const foo = generateTableFunctions([
  'service',
  'payment',
  'certification',
  'provider',
  'provider_certifcation',
  'provider_payment',
  'provider_service'
]);

enter image description here