Share listing setup between the form and the CSV import

Node · Node · intermediate · modification

Moves the "every new listing gets a slug and an audit row" rule out of the routes and into `Listing`'s `beforeCreate` / `afterCreate` hooks, so the form and the import share one definition and the next create path cannot forget it. With the rule in the model, the import no longer needs its row-by-row loop: it validates the file as before and hands the rows to one `bulkCreate` inside the transaction, a single INSERT for the whole file instead of two statements per row. The form route now calls `Listing.create` and still returns the generated slug.

Express 4.21 and Sequelize 6.37 on PostgreSQL 16. `src/db.js` exports the `sequelize` instance. `src/app.js` (unchanged) mounts `app.use('/api/listings', requireAuth, express.json({ limit: '2mb' }), listingsRouter)`; `requireAuth` answers 401 itself unless a host is signed in and sets `req.user = { id }`; the app's error handler logs the error and answers `500 { error: 'internal' }`. `src/lib/listingInput.js` (unchanged): `validateListing(body)` and `validateImport(rows)` return `null` or a list of problems; `validateImport` accepts an array of 1 to 2,000 rows, and both check every field (`title` 1 to 120 characters and `city` 1 to 80 after trimming, `nightlyPriceCents` an integer from 0 to 10,000,000, `maxGuests` an integer from 1 to 50); `listingFields(row)` returns those four fields with the strings trimmed. `makeSlug(title)` (`src/lib/slug.js`, unchanged) returns a lower-case ASCII slug of at most 89 characters ending in 8 random hex digits. `listings.slug` has a unique index and is nullable because listings from before 2023 have none (they are served by id); a slug collision fails the transaction, as it did before this PR. `AuditEvent` (`src/models/auditEvent.js`, unchanged) maps `audit_events (id, entity, entity_id, action, actor_id, created_at)`. Both tables already exist and this PR adds no column, so there is no migration. Nothing else creates listings.

Requirements

Files touched

Review this PR

Node practice