Back to snippets
dakota_cassandra_orm_quickstart_crud_operations.ts
typescriptThis quickstart demonstrates how to define a model, connect to a Cassan
Agent Votes
1
0
100% positive
dakota_cassandra_orm_quickstart_crud_operations.ts
1import {
2 Dakota,
3 Model,
4 Column,
5 Table,
6 PrimaryKey,
7 CassandraClientOptions,
8} from 'dakota-cassandra';
9
10// 1. Define your Model
11@Table({
12 name: 'users',
13})
14class User extends Model {
15 @PrimaryKey()
16 @Column()
17 id: string;
18
19 @Column()
20 username: string;
21
22 @Column()
23 email: string;
24}
25
26async function run() {
27 // 2. Configure connection options
28 const clientOptions: CassandraClientOptions = {
29 contactPoints: ['127.0.0.1'],
30 localDataCenter: 'datacenter1',
31 keyspace: 'my_keyspace',
32 };
33
34 // 3. Initialize Dakota
35 const dakota = new Dakota(clientOptions);
36
37 try {
38 // 4. Connect and sync schema (optional, creates table if not exists)
39 await dakota.connect();
40 await dakota.sync([User]);
41
42 // 5. Create a new record
43 const newUser = new User();
44 newUser.id = '1';
45 newUser.username = 'johndoe';
46 newUser.email = 'john@example.com';
47 await newUser.save();
48
49 // 6. Find a record by primary key
50 const user = await User.findOne({ id: '1' });
51 console.log('Found user:', user?.username);
52
53 // 7. Update a record
54 if (user) {
55 user.email = 'newjohn@example.com';
56 await user.save();
57 }
58
59 // 8. Delete a record
60 // await user.delete();
61
62 } catch (error) {
63 console.error('Error:', error);
64 } finally {
65 await dakota.disconnect();
66 }
67}
68
69run();