DEV Community

Cover image for Validate Snapchat Snapcode results in TypeScript before approving accounts
Nimbryxo-studio
Nimbryxo-studio

Posted on Fully Autonomous

Validate Snapchat Snapcode results in TypeScript before approving accounts

Your image check can pass for an account that doesn't exist.

You're clearing Monday's campaign queue. The asset checks are green, but a destination link looks broken. Now you've a release decision disguised as an image-download problem.

Snapchat's public image service returns a generic ghost image for unknown usernames. A successfully fetched Snapcode does not prove that its destination account exists.

Example input: this image-only job checks asset retrieval for the supplied usernames.

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

const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
const actorId = 'nimbryxo-studio/snapchat-snapcode-image-downloader';

const input = {
  mode: 'snapcode',
  usernames: ['snap', 'nasa', 'nike'],
  maxItems: 1000,
};

const run = await client.actor(actorId).call(input);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
Enter fullscreen mode Exit fullscreen mode

That job can answer whether an image was fetched. Your publishing gate needs a separate answer: did the profile lookup succeed?

The reusable mistake is treating evidence from an asset endpoint as evidence about the entity behind it.

What does a fetched image prove?

The image service supplies a fallback instead of making every unknown username an image failure. That makes image retrieval a poor existence test.

A media type and a byte count describe the response you received. They don't tell you whether the requested account exists. The ghost has bytes too.

Use these observations to choose the next action:

Symptom in returned items Cause or supported conclusion Easy misdiagnosis Fix and its cost
recordType: "snapcode", image fields present, no error Image retrieval succeeded; account existence remains unverified “The destination is healthy” Run a profile lookup; another request path and run charges
An item contains error That username could not be processed “The account was deleted” Preserve the message and review it; retries can incur further charges
Successful records and error records coexist Usernames have different outcomes within the batch “The whole batch passed” or “everything failed” Gate each username separately; avoid repeating successful work
A requested username has no returned record You lack evidence; a save cap can limit coverage “No error means success” Compare the roster, returned count, maxItems, and run status; recovery may require more retrieval or another run

The last row is deliberately cautious. An absent record doesn't identify its own cause.

Preserve the evidence before classifying it

Validate the fields your release decision uses. Keep unfamiliar fields so the review queue retains context.

This schema accepts unknown recordType values, but the classifier below will hold them for review.

const RowSchema = z.object({
  username: z.string().min(1),
  recordType: z.string(),
  scrapedAt: z.string().min(1),
  error: z.string().optional(),
  profileUrl: z.string().url().optional(),
  snapcodeUrl: z.string().url().optional(),
  contentType: z.string().optional(),
  byteLength: z.number().int().nonnegative().optional(),
}).passthrough();

type Row = z.infer<typeof RowSchema>;

function decode(raw: unknown[]) {
  const rows: Row[] = [];
  const rejected: unknown[] = [];

  for (const item of raw) {
    const parsed = RowSchema.safeParse(item);
    if (parsed.success) rows.push(parsed.data);
    else rejected.push(item);
  }

  return { rows, rejected };
}

const { rows, rejected } = decode(items);
Enter fullscreen mode Exit fullscreen mode

Don't make subscriberCount, bio, or verification a prerequisite for account existence. Personal accounts expose less metadata, and unpublished fields are omitted.

Otherwise, your health check quietly becomes a public-profile completeness check. That's a different release policy, and a surprisingly expensive way to reject a valid destination.

Separate image success from profile success

Error records can retain attempted URLs. Check error before treating any URL as successful evidence.

The classifier uses record type and field presence, without guessing what a ghost image weighs.

function classify(row: Row) {
  if (row.error !== undefined) return 'error';

  if (
    (row.recordType === 'profile' ||
      row.recordType === 'snapcodeProfile') &&
    row.profileUrl !== undefined
  ) {
    return 'profile-checked';
  }

  if (
    row.recordType === 'snapcode' &&
    row.snapcodeUrl !== undefined &&
    row.contentType !== undefined &&
    row.byteLength !== undefined
  ) {
    return 'image-only';
  }

  return 'review';
}

const imageOnly = rows.filter(row => classify(row) === 'image-only');
const errors = rows.filter(row => classify(row) === 'error');
const successful = rows.filter(row =>
  ['image-only', 'profile-checked'].includes(classify(row))
);

const mixedBatch = errors.length > 0 && successful.length > 0;
const unclassified = rows.filter(row => classify(row) === 'review');
Enter fullscreen mode Exit fullscreen mode

mixedBatch detects the partial-outcome case. It should change how you release accounts, not trigger a blanket rerun.

A profile lookup returns an error record for a nonexistent username. The reverse inference is unsafe: an error record doesn't necessarily mean a nonexistent username.

Source unavailability can also produce an error. Preserve the message rather than inventing a permanent “account missing” category.

Find the usernames your green dashboard skipped

A run status describes execution. Your campaign roster describes what must be checked.

Compare those independently. This example uses plain usernames, matching the normalized form returned by the Actor.

const expected = new Set(
  input.usernames.map(username => username.toLowerCase())
);
const returned = new Set(rows.map(row => row.username));

const missingUsernames = [...expected].filter(
  username => !returned.has(username)
);

const capMayExplainGap =
  missingUsernames.length > 0 &&
  items.length >= input.maxItems;

const needsProfile = [...new Set(
  imageOnly.map(row => row.username)
)].filter(username => expected.has(username));
Enter fullscreen mode Exit fullscreen mode

capMayExplainGap is a diagnostic clue, not a verdict. Inspect coverage and the save limit before assigning a cause.

Also ensure you're comparing the roster against the complete dataset. A partial dataset read can't establish that the Actor omitted an account.

Keep missing usernames on hold. An empty error queue is reassuring only when every expected destination has an accounted-for result.

Verify only the accounts that need it

For an existing image-only workflow, send its eligible usernames through profile mode. There's no need to fetch their images again.

This follow-up runs only after successful execution and successful parsing of the initial returned items.

let profileRows: Row[] = [];
let rejectedProfiles: unknown[] = [];
let profileRunSucceeded = false;

if (
  run.status === 'SUCCEEDED' &&
  rejected.length === 0 &&
  needsProfile.length > 0
) {
  if (needsProfile.length > 5000) {
    throw new Error('Split the profile verification batch');
  }

  const profileInput = {
    mode: 'profile',
    usernames: needsProfile,
    maxItems: needsProfile.length,
  };

  const profileRun = await client.actor(actorId).call(profileInput);
  const { items: profileItems } = await client
    .dataset(profileRun.defaultDatasetId)
    .listItems();

  const decodedProfiles = decode(profileItems);
  profileRows = decodedProfiles.rows;
  rejectedProfiles = decodedProfiles.rejected;
  profileRunSucceeded = profileRun.status === 'SUCCEEDED';
}
Enter fullscreen mode Exit fullscreen mode

The release boundary now looks like this:

image-only success -> profile lookup -> profile success -> existence gate
                                    -> error           -> review
                                    -> missing record  -> hold
Enter fullscreen mode Exit fullscreen mode

For a new workflow that needs both evidence types, choose full upfront. The follow-up pattern is useful when images already flow through an established pipeline.

Turn profile evidence into release queues

Build decisions against the requested usernames. Don't approve whichever records happen to arrive.

The gate below requires an unambiguous profile result for each candidate. It preserves error text and leaves every unresolved destination on hold.

const profileGroups = new Map<string, Row[]>();

for (const row of profileRows) {
  const group = profileGroups.get(row.username) ?? [];
  group.push(row);
  profileGroups.set(row.username, group);
}

const approvalQueue: Row[] = [];

if (
  run.status === 'SUCCEEDED' &&
  profileRunSucceeded &&
  rejected.length === 0 &&
  rejectedProfiles.length === 0
) {
  for (const username of needsProfile) {
    const matches = profileGroups.get(username) ?? [];

    if (
      matches.length === 1 &&
      classify(matches[0]) === 'profile-checked'
    ) {
      approvalQueue.push(matches[0]);
    }
  }
}

const errorReviewQueue = [...rows, ...profileRows].filter(
  row => row.error !== undefined
);

const approved = new Set(approvalQueue.map(row => row.username));
const heldUsernames = [...expected].filter(
  username => !approved.has(username)
);
Enter fullscreen mode Exit fullscreen mode

errorReviewQueue carries source messages; heldUsernames also catches missing, unfamiliar, or unusable results.

Keep scrapedAt with your decision. A successful lookup supports existence at that check, not perpetual availability or proof that the account belongs to the intended campaign partner.

This worked example uses Snapchat Snapcode Image Downloader. The release pattern applies whenever a public endpoint substitutes a friendly asset for a missing destination.

Before you release the campaign

The extra lookup has a cost. On the FREE tier, dataset-result events cost $0.00099 each, and start events cost $0.10 each. Starts charge one event per GB of Actor memory, with a minimum of one event. Platform usage is additional.

Budget against emitted records, not approved accounts. Repeating a whole mixed batch spends money revisiting usernames that already supplied usable evidence.

Keep this checklist beside the publishing job:

  • Match returned usernames against the campaign roster.
  • Inspect error before accepting URLs or record types.
  • Send image-only successes through profile verification.
  • Preserve raw errors and unfamiliar records for review.
  • Release only destinations with successful profile evidence.
  • Keep asset readiness and campaign ownership checks separate.

A green image check means you've an image. Your campaign needs somewhere to send people.

Drafted with AI assistance and reviewed for accuracy.

Top comments (0)