Skip to content

Commit

Permalink
Merge pull request #63 from cofacts/add-user-to-events
Browse files Browse the repository at this point in the history
Add user to events
  • Loading branch information
MrOrz authored May 19, 2023
2 parents 58f3362 + b2112f2 commit f731bce
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 29 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ Please manually create dataset, handle permission on Google Cloud, and setup rel

Run the following script to create big query tables under the dataset specified in the environment variable.
```
./node_modules/.bin/babel-node db/createBqTables.ts --extensions .ts,.js
./node_modules/.bin/babel-node db/setBqTables.ts --extensions .ts,.js
```

---
Expand Down
1 change: 1 addition & 0 deletions bq/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { convert } from 'zoq';
export const TABLE = 'events';

const eventBatchSchema = z.object({
userId: z.string().nullable(),
createdAt: z.date().describe('Time of the event batch is sent'),
text: z.string().describe('Message text').nullable(),
messageSource: z.enum(['user', 'group', 'room']).nullable(),
Expand Down
28 changes: 0 additions & 28 deletions db/createBqTables.ts

This file was deleted.

38 changes: 38 additions & 0 deletions db/setBqTables.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* BigQuery client and schema
*/
import 'dotenv/config';
import { BigQuery } from '@google-cloud/bigquery';
import type { TableSchema } from '@google-cloud/bigquery';
import * as bqEvents from '../bq/events';

const bqDataset = new BigQuery().dataset(
process.env.BIGQUERY_ANALYTICS_DATASET || ''
);

async function loadSchema({TABLE, SCHEMA}: {TABLE: string, SCHEMA: TableSchema[]}) {
const table = bqDataset.table(TABLE);

if(await table.exists()) {
const [result] = await table.setMetadata({schema: SCHEMA});

console.log(`Table ${table.id} fields updated to:`, result.schema.fields);
return;
}

const [createdTable] = await bqDataset.createTable(TABLE, {
schema: SCHEMA,
timePartitioning: {
type: 'MONTH',
field: 'createdAt',
},
});

console.log(`Table ${table.id} created under dataset ${createdTable.dataset.id}.`);
console.log('You may need to wait up to 2 minutes before seeing it in GCS console.');
}

loadSchema(bqEvents).catch((e) => {
console.error('[setBqTables]', e);
process.exit(1);
});

0 comments on commit f731bce

Please sign in to comment.