/
actor.ts
76 lines (64 loc) · 2.02 KB
/
actor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { Actor, HttpAgent, Identity } from "@dfinity/agent";
import {
idlFactory as CanCan_idl,
canisterId as CanCan_canister_id,
} from "dfx-generated/CanCan";
import _SERVICE from "./typings";
import dfxConfig from "../../../dfx.json";
const DFX_NETWORK = process.env.DFX_NETWORK || "local";
const isLocalEnv = DFX_NETWORK === "local";
function getHost() {
// Setting host to undefined will default to the window location 👍🏻
return isLocalEnv ? dfxConfig.networks.local.bind : undefined;
}
const host = getHost();
function createActor(identity?: Identity) {
const agent = new HttpAgent({ host, identity });
const actor = Actor.createActor<_SERVICE>(CanCan_idl, {
agent,
canisterId: CanCan_canister_id,
});
return { actor, agent };
}
/*
* Responsible for keeping track of the actor, whether the user has logged
* in again or not. A logged in user uses a different actor with their
* Identity, to ensure their Principal is passed to the backend.
*/
class ActorController {
_actor: Promise<_SERVICE>;
_isAuthenticated: boolean = false;
constructor() {
this._actor = this.initBaseActor();
}
async initBaseActor(identity?: Identity) {
const { agent, actor } = createActor(identity);
// The root key only has to be fetched for local development environments
if (isLocalEnv) {
await agent.fetchRootKey();
}
return actor;
}
/*
* Get the actor instance to run commands on the canister.
*/
get actor() {
return this._actor;
}
/*
* Once a user has authenticated and has an identity pass this identity
* to create a new actor with it, so they pass their Principal to the backend.
*/
async authenticateActor(identity: Identity) {
this._actor = this.initBaseActor(identity);
this._isAuthenticated = true;
}
/*
* If a user unauthenticates, recreate the actor without an identity.
*/
unauthenticateActor() {
this._actor = this.initBaseActor();
this._isAuthenticated = false;
}
}
export const actorController = new ActorController();