Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | 131x 131x 110x 110x 110x 110x 110x 110x 110x 7x 14x 7x 7x 7x 14x 14x 7x 14x 14x 14x 4x 10x 10x 8x 3x 2x 2x 11x 11x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 46x 31x 25x 13x 13x 1x 19x 13x 13x 18x 4x 4x 3x | import type { AnyModel, CountOptions, ModelStatic, Values } from '../model/options.ts';
import { ModelRegistry } from '../model/model-registry.ts';
import { Association, type AccessorOptions } from './association.ts';
import { AssociationKeys } from './association-keys.ts';
import { JunctionKeys } from './junction-keys.ts';
import type { AssociationThrough, BelongsToManyOptions } from './types.ts';
const registry = new ModelRegistry();
type Model = ModelStatic<AnyModel>;
type Instance = AnyModel;
type JoinOptions = Readonly<{ joinTableAttributes?: readonly string[] }>;
type LinkOptions = AccessorOptions & Readonly<{ through?: Values }>;
const junctionKeys = new JunctionKeys(new AssociationKeys());
/**
* `source.belongsToMany(target, { through })` (Sequelize v6 `BelongsToMany`): both foreign keys
* live on a junction model, which is created when given by name.
*/
export class BelongsToMany<
S extends AnyModel = AnyModel,
T extends AnyModel = AnyModel,
> extends Association<S, T> {
readonly #junction: Model;
readonly #junctionName: string;
readonly #otherKey: string;
/**
* Adds the foreign key attributes to the junction model and registers the association.
*
* @param source - Model the association is defined on.
* @param target - Associated model.
* @param options - Association options with `through`.
*/
constructor(source: ModelStatic<S>, target: ModelStatic<T>, options: BelongsToManyOptions) {
const resolved = junctionKeys.resolve(source, target, options);
const model = (resolved.keys.through as AssociationThrough).model;
super('BelongsToMany', source, target, options, resolved.name, resolved.keys);
this.#junction = model;
this.#junctionName = registry.state(model).definition.name;
this.#otherKey = resolved.keys.otherKey as string;
this.install();
}
/**
* Loads the associated instances, each with its junction row under the junction model name
* (`getXs`).
*
* @param instance - Source instance.
* @param options - Find options.
* @returns Associated instances.
*/
async get(instance: Instance, options: AccessorOptions = {}): Promise<Instance[]> {
const joined = await this.#links(instance, options);
const byKey = new Map(joined.map((link) => [link.get(this.#otherKey), link]));
const rows = (await this.target.findAll({
...options,
where: this.andWhere(options.where, this.scope, { [this.targetKey]: [...byKey.keys()] }),
} as never)) as Instance[];
const attributes = (options as JoinOptions).joinTableAttributes;
rows.forEach((row) => {
const link = byKey.get(this.#rowKey(row, options));
this.#attach(row, link as Instance, attributes, options.raw === true);
});
return rows;
}
#rowKey(row: Instance, options: AccessorOptions): unknown {
return options.raw === true
? (row as unknown as Values)[this.targetKey]
: row.get(this.targetKey);
}
#attach(
row: Instance,
link: Instance,
attributes: readonly string[] | undefined,
raw: boolean,
): void {
const names = attributes ?? Object.keys(link.dataValues as Values);
if (raw) {
names.forEach((name) => {
(row as unknown as Values)[`${this.#junctionName}.${name}`] = link.get(name);
});
} else if (attributes === undefined || names.length > 0) {
(row.dataValues as Values)[this.#junctionName] = link;
}
}
/**
* Counts the associated instances (`countXs`).
*
* @param instance - Source instance.
* @param options - Count options.
* @returns Number of associated rows.
*/
async count(instance: Instance, options: AccessorOptions = {}): Promise<number> {
const linked = (await this.#links(instance, options)).map((link) => link.get(this.#otherKey));
return this.target.count({
...options,
where: this.andWhere(options.where, this.scope, { [this.targetKey]: linked }),
} as CountOptions);
}
/**
* Checks whether all given instances are associated (`hasX` / `hasXs`).
*
* @param instance - Source instance.
* @param items - Instance(s) or target key value(s).
* @param options - Query options.
* @returns True when every item is associated.
*/
async has(instance: Instance, items: unknown, options: AccessorOptions = {}): Promise<boolean> {
return (
(await this.#links(instance, options, this.#ids(items))).length === this.#ids(items).length
);
}
/**
* Creates the missing junction rows (`addX` / `addXs`).
*
* @param instance - Source instance.
* @param items - Instance(s) or target key value(s).
* @param options - Query options; `through` gives junction values.
* @returns The source instance.
*/
async add(instance: Instance, items: unknown, options: LinkOptions = {}): Promise<Instance> {
await this.#addLinks(instance, items, options);
return instance;
}
/**
* Deletes the junction rows (`removeX` / `removeXs`).
*
* @param instance - Source instance.
* @param items - Instance(s) or target key value(s).
* @param options - Query options.
* @returns The source instance.
*/
async remove(
instance: Instance,
items: unknown,
options: AccessorOptions = {},
): Promise<Instance> {
await this.#removeLinks(instance, items, options);
return instance;
}
/**
* Replaces the associated instances: deletes stale junction rows, adds missing ones (`setXs`).
*
* @param instance - Source instance.
* @param items - Instance(s) or target key value(s).
* @param options - Query options; `through` gives junction values.
* @returns The source instance.
*/
async set(instance: Instance, items: unknown, options: LinkOptions = {}): Promise<Instance> {
const wanted = new Set(this.#ids(items));
const stale = (await this.#links(instance, options))
.map((link) => link.get(this.#otherKey))
.filter((id) => !wanted.has(id));
await this.#removeLinks(instance, stale, options);
await this.#addLinks(instance, items, options);
return instance;
}
/**
* Creates an associated instance and its junction row (`createX`).
*
* @param instance - Source instance.
* @param values - Values of the new instance.
* @param options - Query options; `through` gives junction values.
* @returns The created instance.
*/
async create(
instance: Instance,
values: Values = {},
options: LinkOptions = {},
): Promise<Instance> {
const created = (await this.target.create(
{ ...values, ...this.scope } as never,
this.passThrough(options) as never,
)) as Instance;
await this.#addLinks(instance, created, options);
return created;
}
#own(instance: Instance): Values {
return { [this.foreignKey]: instance.get(this.sourceKey), ...this.through?.scope };
}
#ids(items: unknown): readonly unknown[] {
return this.toArray(items).map((item) => this.keyOf(item, this.targetKey));
}
#links(
instance: Instance,
options: AccessorOptions,
wanted?: readonly unknown[],
): Promise<Instance[]> {
return this.#junction.findAll({
...this.passThrough(options),
where: this.andWhere(
this.#own(instance),
wanted === undefined ? undefined : { [this.#otherKey]: wanted },
),
} as never) as Promise<Instance[]>;
}
async #addLinks(instance: Instance, items: unknown, options: LinkOptions): Promise<void> {
const wanted = this.#ids(items);
const existing = new Set(
(await this.#links(instance, options, wanted)).map((link) => link.get(this.#otherKey)),
);
const missing = wanted.filter((id) => !existing.has(id));
Eif (missing.length > 0) {
await this.#junction.bulkCreate(
missing.map((id) => ({
...options.through,
...this.#own(instance),
[this.#otherKey]: id,
})) as never,
this.passThrough(options) as never,
);
}
}
async #removeLinks(instance: Instance, items: unknown, options: AccessorOptions): Promise<void> {
const wanted = this.#ids(items);
if (wanted.length > 0) {
await this.#junction.destroy({
...this.passThrough(options),
where: this.andWhere(this.#own(instance), { [this.#otherKey]: wanted }),
} as never);
}
}
}
|