As I was implementing an Object Mapper, I wanted to attach custom query. Turns out the only
itself. What if you can make it accept a custom type or default back to the T passed to the ModelMapper. The only work around I got is to do 'an unknown as MyType' on the newly attached function.
import cassandra from 'cassandra-driver';
import { cassandraClient } from '@libs/cassandra-client';
/** Create a mapper for the company balance model. */
const mapper = new cassandra.mapping.Mapper(cassandraClient, {
models: {
CompanyBalance: {
tables: ['company_balance'],
mappings: new cassandra.mapping.UnderscoreCqlToCamelCaseMappings(),
columns: {
company_id: {
name: 'companyId',
toModel: (val) => val.toString(),
},
balance: {
name: 'balance',
toModel: (val) => Number(val),
},
},
},
},
});
type CompanyBalance = {
companyId: string;
balance: number;
};
interface CompanyBalanceMapper
extends cassandra.mapping.ModelMapper<CompanyBalance> {
/**
* Updates the balance of a company.
*
* @param {{ companyId: string; balance: number }} params An object with the
* company ID and the new balance.
*/
updateBalance: (params: {
/**
* The amount to add (+ve) or amount to deduct (-ve) from the current
* balance
*/
balance: number;
/** The ID of the company to update the balance for */
companyId: string;
}) => Promise<cassandra.mapping.Result<null>>;
}
/** Manage Company Balance */
const CompanyBalance = mapper.forModel(
'CompanyBalance',
) as CompanyBalanceMapper;
/**
* Attach update balance to the object. This is composed of the query and
* parameters you want to pass into the query. Make sure the parameters' length
* and the question marks count in your query match.
*/
CompanyBalance.updateBalance = CompanyBalance.mapWithQuery(
'UPDATE company_balance SET balance = balance + ? WHERE company_id = ?;',
(props: { balance: number; companyId: string }) => Object.values(props),
) as unknown as CompanyBalanceMapper['updateBalance'];
export default CompanyBalance;
Thanks.