MCPcopy
hub / github.com/sequelize/sequelize / findCreateFind

Method findCreateFind

src/model.js:2479–2513  ·  view source on GitHub ↗

* A more performant findOrCreate that may not work under a transaction (working in postgres) * Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again * * @see * Model.findAll for a full specification of find and options *

(options)

Source from the content-addressed store, hash-verified

2477 * @returns {Promise<Model,boolean>}
2478 */
2479 static async findCreateFind(options) {
2480 if (!options || !options.where) {
2481 throw new Error(
2482 'Missing where attribute in the options parameter passed to findCreateFind.'
2483 );
2484 }
2485
2486 let values = { ...options.defaults };
2487 if (_.isPlainObject(options.where)) {
2488 values = Utils.defaults(values, options.where);
2489 }
2490
2491
2492 const found = await this.findOne(options);
2493 if (found) return [found, false];
2494
2495 try {
2496 const createOptions = { ...options };
2497
2498 // To avoid breaking a postgres transaction, run the create with `ignoreDuplicates`.
2499 if (this.sequelize.options.dialect === 'postgres' && options.transaction) {
2500 createOptions.ignoreDuplicates = true;
2501 }
2502
2503 const created = await this.create(values, createOptions);
2504 return [created, true];
2505 } catch (err) {
2506 if (!(err instanceof sequelizeErrors.UniqueConstraintError || err instanceof sequelizeErrors.EmptyResultError)) {
2507 throw err;
2508 }
2509
2510 const foundAgain = await this.findOne(options);
2511 return [foundAgain, false];
2512 }
2513 }
2514
2515 /**
2516 * Insert or update a single row. An update will be executed if a row which matches the supplied values on either the primary key or a unique key is found. Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.

Callers 3

create.test.jsFile · 0.80
model.tsFile · 0.80

Calls 2

findOneMethod · 0.95
createMethod · 0.95

Tested by

no test coverage detected