DEV Community

Cover image for Comparing Zoopla data in TypeScript without inventing price-change dates
Nimbryxo-studio
Nimbryxo-studio

Posted on Fully Autonomous

Comparing Zoopla data in TypeScript without inventing price-change dates

Your Friday price chart can look like sales evidence without containing a single transaction.

You're wiring a weekly report, and lastModified looks temptingly close to a price-change timestamp. It's an attractive shortcut.

The Actor extracts current listing data, excluding historical sold-price timelines. Repeated imports establish observed asking prices; they can't establish completed sales or transaction prices.

What does a change between imports prove?

A listing describes an advertisement. Don't promote its lastModified value into evidence of a price-change event.

Your useful result is narrower: the price returned for an advertisement differed between accepted imports. That comparison doesn't establish exactly when the underlying edit happened.

Start by fixing the collection scope rather than treating every import as an interchangeable market sample.

This Example input selects a search page and bounds the collection.

import { ApifyClient } from 'apify-client';
import { z } from 'zod';
import pg from 'pg';

const input = z.object({
  searchUrls: z.array(z.string().url()).min(1),
  maxItems: z.number().int().min(1).max(500),
}).strict().parse({
  searchUrls: [
    'https://www.zoopla.co.uk/for-sale/property/manchester/',
  ],
  maxItems: 20,
});

const source =
  'nimbryxo-studio/zoopla-uk-property-listings-and-lease-details';

const client = new ApifyClient({
  token: process.env.APIFY_TOKEN,
});
Enter fullscreen mode Exit fullscreen mode

Leave the preset residential GB proxy configuration intact. The source blocks datacenter IPs at the network edge.

A search URL supplies listings from its results page. Increasing maxItems doesn't turn that page into a complete inventory.

That matters later: disappearance from your sample can't establish withdrawal, completion, or even removal from the source.

Make collection and consumption separate retries

Starting another collection and reading an existing dataset are different operations.

Use the run ID as the ingestion batch identity. Replaying that dataset should preserve existing observations; starting another run should create another observation opportunity.

This starts a collection unless you supply an existing run ID, then waits and reads its dataset.

const runId = process.env.INGEST_RUN_ID
  ?? (await client.actor(source).start(input)).id;

const run = await client.run(runId).waitForFinish();

if (!run || ![
  'SUCCEEDED', 'FAILED', 'TIMED-OUT', 'ABORTED',
].includes(run.status)) {
  throw new Error('Collection has not reached a terminal state');
}

const { items } = await client
  .dataset(run.defaultDatasetId)
  .listItems();

const batchId = run.id;
Enter fullscreen mode Exit fullscreen mode

Have your scheduler retain the run ID for consumer retries. Without INGEST_RUN_ID, another invocation starts another collection.

There's still a boundary here: starting the Actor and retaining its ID aren't an atomic operation. A crash between them can create another run. Database idempotency can't undo that start.

Reject a price you can't interpret

TypeScript doesn't validate dataset contents. Treat every item as untrusted until its monitored fields pass.

The following schema is deliberately a consumer contract. It requires an advertisement identity and an offset-bearing scrapedAt value. Other timestamps receive the same format check when present.

It also refuses formatted price strings. Guessing how to remove currency symbols and qualifiers would hide a contract change.

This validates candidate observations and quarantines invalid records, duplicate identities, and items from unsuccessful runs.

const timestamp = z.string().datetime({ offset: true });

const Listing = z.object({
  id: z.string().min(1),
  scrapedAt: timestamp,
  price: z.number().finite().nonnegative().optional(),
  priceCurrency: z.string().regex(/^[A-Z]{3}$/).optional(),
  priceLabel: z.string().min(1).optional(),
  listingType: z.string().min(1).optional(),
  listingStatus: z.string().min(1).optional(),
  publishedAt: timestamp.optional(),
  lastModified: timestamp.optional(),
}).passthrough();

const inspected = items.map((raw: unknown, itemIndex: number) => ({
  raw,
  itemIndex,
  parsed: Listing.safeParse(raw),
}));

const identityCounts = new Map<string, number>();

for (const item of inspected) {
  if (item.parsed.success) {
    const id = item.parsed.data.id;
    identityCounts.set(id, (identityCounts.get(id) ?? 0) + 1);
  }
}

const accepted: Array<z.infer<typeof Listing>> = [];
const rejected: Array<{
  item_index: number;
  raw: unknown;
  reasons: string[];
}> = [];

for (const item of inspected) {
  const reasons = item.parsed.success
    ? []
    : item.parsed.error.issues.map(issue =>
        `${issue.path.join('.')}: ${issue.message}`);

  if (run.status !== 'SUCCEEDED') {
    reasons.push(`Collection status: ${run.status}`);
  }

  if (
    item.parsed.success
    && (identityCounts.get(item.parsed.data.id) ?? 0) > 1
  ) {
    reasons.push('Duplicate advertisement identity within dataset');
  }

  if (reasons.length) {
    rejected.push({
      item_index: item.itemIndex,
      raw: item.raw,
      reasons,
    });
  } else if (item.parsed.success) {
    accepted.push(item.parsed.data);
  }
}
Enter fullscreen mode Exit fullscreen mode

The uppercase currency rule is our acceptance policy, not a promise about every returned value.

Using .strict() here would also reject unrelated listing details. .passthrough() retains those fields while validating the fields that control your report.

The trade-off is explicit: additive fields won't page you. Changed price types and unexpected timestamp formats will.

A failing optional timestamp rejects the whole record. Leaving a gap is safer than quietly accepting the price while discarding evidence that its surrounding contract changed.

Give advertisements and observations different keys

Use (source, id) for the current advertisement. Include batch_id for an observation.

That distinction gives retries somewhere harmless to land.

dataset item
    |
    +-- rejected -----------------> quarantine
    |
    +-- accepted -----------------> observation history
                                        |
                                        +-- greater scrapedAt --> current pointer
Enter fullscreen mode Exit fullscreen mode

The advertisement key supports repeated imports of the same source identity. It doesn't establish property identity across relistings or sources.

If an identity is reused, or a relisting receives another identity, this key isn't enough for property-level history. Add an explicit matching process rather than merging addresses and hoping.

Keep typed columns for comparisons and indexes. Keep raw JSONB for qualifiers, audit, and later interpretation.

This creates separate storage for batches, observations, current pointers, and rejected records.

const pool = new pg.Pool();

const schemaSql = `
CREATE TABLE IF NOT EXISTS ingest_batches (
  source text NOT NULL, batch_id text NOT NULL,
  dataset_id text NOT NULL, run_status text NOT NULL,
  PRIMARY KEY (source, batch_id)
);

CREATE TABLE IF NOT EXISTS listing_observations (
  source text NOT NULL, batch_id text NOT NULL,
  listing_id text NOT NULL, scraped_at timestamptz NOT NULL,
  price numeric, currency text, price_label text, listing_type text,
  raw jsonb NOT NULL,
  PRIMARY KEY (source, batch_id, listing_id),
  FOREIGN KEY (source, batch_id)
    REFERENCES ingest_batches (source, batch_id)
);

CREATE TABLE IF NOT EXISTS listing_current (
  source text NOT NULL, listing_id text NOT NULL,
  batch_id text NOT NULL, scraped_at timestamptz NOT NULL,
  PRIMARY KEY (source, listing_id),
  FOREIGN KEY (source, batch_id, listing_id)
    REFERENCES listing_observations (source, batch_id, listing_id)
);

CREATE TABLE IF NOT EXISTS ingest_rejects (
  source text NOT NULL, batch_id text NOT NULL,
  item_index integer NOT NULL, raw jsonb NOT NULL, reasons jsonb NOT NULL,
  PRIMARY KEY (source, batch_id, item_index),
  FOREIGN KEY (source, batch_id)
    REFERENCES ingest_batches (source, batch_id)
);
`;
Enter fullscreen mode Exit fullscreen mode

The current table points to an immutable observation. An operational lookup joins that pointer to the observation, avoiding another copy of the listing payload.

JSONB costs storage and can retain fields your report never uses. Keep an appropriate retention policy. Typed columns alone, however, would discard the wording needed to interpret an asking price.

Commit accepted records and quarantine together

A database failure should leave neither half an import nor a misleading current pointer.

A validation failure has different semantics: preserve the rejected item, accept valid siblings, and flag the batch for attention.

This transaction writes each collection in bulk. Its current-state policy advances the pointer only when the supplied scrapedAt value exceeds the stored value.

async function ingestBatch(): Promise<void> {
  const db = await pool.connect();

  try {
    await db.query('BEGIN');

    await db.query(`
      INSERT INTO ingest_batches
        (source, batch_id, dataset_id, run_status)
      VALUES ($1, $2, $3, $4)
      ON CONFLICT DO NOTHING
    `, [source, batchId, run.defaultDatasetId, run.status]);

    await db.query(`
      WITH payload AS (
        SELECT value AS raw
        FROM jsonb_array_elements($3::jsonb)
      ), saved AS (
        INSERT INTO listing_observations (
          source, batch_id, listing_id, scraped_at,
          price, currency, price_label, listing_type, raw
        )
        SELECT $1, $2, raw->>'id',
          (raw->>'scrapedAt')::timestamptz,
          (raw->>'price')::numeric,
          raw->>'priceCurrency', raw->>'priceLabel',
          raw->>'listingType', raw
        FROM payload
        ON CONFLICT DO NOTHING
        RETURNING source, listing_id, batch_id, scraped_at
      )
      INSERT INTO listing_current
        (source, listing_id, batch_id, scraped_at)
      SELECT source, listing_id, batch_id, scraped_at FROM saved
      ON CONFLICT (source, listing_id) DO UPDATE
      SET batch_id = EXCLUDED.batch_id,
          scraped_at = EXCLUDED.scraped_at
      WHERE EXCLUDED.scraped_at > listing_current.scraped_at
    `, [source, batchId, JSON.stringify(accepted)]);

    await db.query(`
      INSERT INTO ingest_rejects
        (source, batch_id, item_index, raw, reasons)
      SELECT $1, $2, r.item_index, r.raw, r.reasons
      FROM jsonb_to_recordset($3::jsonb)
        AS r(item_index integer, raw jsonb, reasons jsonb)
      ON CONFLICT DO NOTHING
    `, [source, batchId, JSON.stringify(rejected)]);

    await db.query('COMMIT');
  } catch (error) {
    await db.query('ROLLBACK');
    throw error;
  } finally {
    db.release();
  }
}
Enter fullscreen mode Exit fullscreen mode

Replaying a committed batch inserts nothing. A failed transaction can be retried without doubling its observations.

This assumes a finished dataset remains unchanged during consumption. If you need to reprocess it under changed validation rules, use an explicit processing version and reconciliation job. These immutable keys intentionally prevent silent replacement.

An unsuccessful collection contributes quarantine records, not accepted observations. That conservative choice sacrifices potentially useful partial data to keep the published report's acceptance rule simple.

Compare asks without changing their meaning

The code uses scrapedAt as an ordering key. That's a consumer policy, not independent verification of when the source was observed or edited.

Keep the supplied timestamps as metadata. None should become a transaction timestamp or an exact price-change timestamp in your report.

The report should distinguish these cases:

Comparison Treatment
Numeric prices with matching currency and listing type Candidate asking-price delta
Missing price or currency No numeric comparison
Changed currency or listing type Review comparability
Changed priceLabel Review qualifiers and rental terms
Equal scrapedAt values Review ordering ambiguity

Label changes deserve attention even when the arithmetic works. An amount can change alongside its meaning.

This rebuilds comparisons from stored history, flags ambiguous neighboring observations, and closes the shared pool once.

try {
  await pool.query(schemaSql);
  await ingestBatch();

  const comparisons = await pool.query(`
    WITH samples AS (
      SELECT *,
        count(*) OVER (
          PARTITION BY source, listing_id, scraped_at
        ) AS simultaneous
      FROM listing_observations
      WHERE source = $1
    ), sequenced AS (
      SELECT *,
        lag(scraped_at) OVER w AS previous_at,
        lag(price) OVER w AS previous_price,
        lag(currency) OVER w AS previous_currency,
        lag(listing_type) OVER w AS previous_type,
        lag(price_label) OVER w AS previous_label,
        lag(simultaneous) OVER w AS previous_simultaneous
      FROM samples
      WINDOW w AS (
        PARTITION BY source, listing_id
        ORDER BY scraped_at, batch_id
      )
    )
    SELECT *,
      CASE WHEN currency = previous_currency
        AND listing_type = previous_type
        AND simultaneous = 1 AND previous_simultaneous = 1
        AND scraped_at > previous_at
      THEN price - previous_price END AS observed_ask_delta,
      (
        price IS NULL OR previous_price IS NULL
        OR currency IS NULL OR previous_currency IS NULL
        OR currency IS DISTINCT FROM previous_currency
        OR listing_type IS NULL OR previous_type IS NULL
        OR listing_type IS DISTINCT FROM previous_type
        OR price_label IS NULL OR previous_label IS NULL
        OR price_label IS DISTINCT FROM previous_label
        OR simultaneous > 1 OR previous_simultaneous > 1
      ) AS needs_review
    FROM sequenced
    WHERE previous_at IS NOT NULL
  `, [source]);

  if (
    rejected.length
    || !accepted.length
    || run.status !== 'SUCCEEDED'
    || comparisons.rows.some(row => row.needs_review)
  ) {
    process.exitCode = 1;
  }
} finally {
  await pool.end();
}
Enter fullscreen mode Exit fullscreen mode

observed_ask_delta is a candidate, not approval to publish. Resolve needs_review before including a comparison in the report.

Rebuilding comparisons also handles late imports: an inserted historical observation can change which records are neighbors. At larger volumes, recompute affected advertisement histories instead of scanning the full series.

Equal scrapedAt values leave the current pointer unchanged. The report flags the tied observations and their following comparison rather than inventing an order from run identifiers.

A finished run can still be unusable

The Zoopla UK Property Listings and Lease Details Scraper returns a status record instead of listings when every attempt is blocked. Completion alone therefore isn't your acceptance signal.

The validator routes records without the required observation shape to quarantine. An empty accepted collection also sets a failing exit status.

Fields omitted by a listing remain absent in its raw snapshot. In typed storage, missing prices remain nullable; nothing carries forward an earlier price and presents it as newly observed.

Connect the exit status to your scheduler's alerting. Include the batch ID and quarantine location, then distinguish:

  • Collection failure from record validation failure.
  • Missing accepted observations from ordinary sample turnover.
  • Currency, timestamp, and comparison-term review from additive fields.

Persistent historical review flags will keep this example's exit status failing. A scheduled production report needs an acknowledgment ledger so resolved findings stop paging you.

No listingStatus value creates a transaction record in this design. Transaction-based valuation needs a separately sourced transaction dataset and an explicit matching process.

Before Friday's report ships

  • Replay the existing run when retrying consumption.
  • Keep rejected raw records beside accepted observations.
  • Check sample coverage before interpreting disappearances.
  • Resolve currency, timestamp, and label review flags.
  • Label the chart observed asking prices.

A quieter advertisement is still an advertisement.

Drafted with AI assistance and reviewed for accuracy.

Top comments (0)