Skip to content

Instantly share code, notes, and snippets.

@mhassanist
Last active February 12, 2022 12:20
Show Gist options
  • Save mhassanist/219ff4917e647e7dbe035e3190e126c2 to your computer and use it in GitHub Desktop.
Save mhassanist/219ff4917e647e7dbe035e3190e126c2 to your computer and use it in GitHub Desktop.
import { PersistentVector, PersistentMap } from "near-sdk-core";
@nearBindgen
class Organization {
name: string;
about: string;
orgId: string;
constructor(name: string, about: string, orgId: string) {
this.name = name;
this.about = about;
this.orgId = orgId;
}
}
@nearBindgen
export class Contract {
//PersistentVector is required to keep track of the keys.
keys: PersistentVector<string> = new PersistentVector<string>("keys");
organizations: PersistentMap<string, Organization> = new PersistentMap<
string,
Organization
>("orgs"); //key:orgCode, value: org object. Value could be of any type.
@mutateState()
addOrganization(orgId: string, orgName: string, orgAbout: string): string {
orgId = orgId.toUpperCase(); //Uppercase organization IDs to ease comparisons.
let o = new Organization(orgName, orgAbout, orgId);
this.keys.push(orgId); //save the keys here while saving the value objects
this.organizations.set(orgId, o);
return "Organization created with code= " + orgId + " and name= " + orgName;
}
getOrganizations(): Map<string, Organization> {
//maps can't be returned directly. You need to copy the values to a temp normal map and return it
const res: Map<string, Organization> = new Map<string, Organization>();
for (let i = 0; i < this.keys.length; i++) {
res.set(this.keys[i], this.organizations.getSome(this.keys[i]));
}
return res;
}
//if you gonna need delete for any reason, u have to maintain the keys vector deletion as well.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment