Function Reference
# The code runtime built into the server includes a module with functions to implement various logic and custom behavior, enabling you to define authoritative code and conditions on input received by clients. Learn more about it in the Server Framework documentation.
This page lists all functions available within Nakama and their respective parameters, with corresponding code samples for each.
If you haven’t already, see the documentation on using the server framework .
Writing custom SQL is discouraged in favor of using the built-in features of the Storage Engine. If custom SQL is needed for your use case, please
contact Heroic Labs before proceeding.
The creation of custom tables is strongly discouraged.
Accounts
# accountDeleteId
# Delete an account by user ID.
Parameters Name Default Description userId
string
REQUIRED User ID for the account to be deleted. Must be valid UUID. recorded
bool false Whether to record this deletion in the database. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let userId = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
try {
nk . accountDeleteId ( userId , false );
} catch ( error ) {
// handle error
}
accountExportId
# Export account information for a specified user ID.
Parameters Name Default Description userId
string
REQUIRED User ID for the account to be exported. Must be valid UUID. Returns Name Description export
string Account information for the provided user ID, in JSON format. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let userId = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
try {
let accountJson = nk . accountExportId ( userId );
} catch ( error ) {
// handle error
}
accountGetId
# Fetch account information by user ID.
Parameters Name Default Description userId
string
REQUIRED User ID to fetch information for. Must be valid UUID. Returns Name Description account
nkruntime.Account All account information including wallet, device IDs and more. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let userId = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
try {
let account = nk . accountGetId ( userId );
} catch ( error ) {
// handle error
}
accountsGetId
# Fetch information for multiple accounts by user IDs.
Parameters Name Default Description userIds
[]string
REQUIRED Array of user IDs to fetch information for. Must be valid UUID. Returns Name Description account
nkruntime.Account[] Array of accounts. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let userIds = [ '4ec4f126-3f9d-11e7-84ef-b7c182b36521' , '6134d1cf-4b55-497f-b9e9-fc5090b76475' ];
try {
let accounts = nk . accountsGetId ( userIds );
} catch ( error ) {
// handle error
}
accountUpdateId
# Update an account by user ID.
Parameters Name Default Description userId
string
REQUIRED User ID for which the information is to be updated. Must be valid UUID. metadata
object The metadata to update for this account. username
string Username to be set. Must be unique. Use null if it is not being updated. displayName
string Display name to be updated. Use null if it is not being updated. timezone
string Timezone to be updated. Use null if it is not being updated. location
string Location to be updated. Use null if it is not being updated. language
string Lang tag to be updated. Use null if it is not being updated. avatarUrl
string User's avatar URL. Use null if it is not being updated. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
let userId = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let username = null ;
let metadata = { pro : true };
let displayName = 'new display name' ;
let timezone = null ;
let location = null ;
let langTag = null ;
let avatarUrl = null ;
try {
nk . accountUpdateId ( userId , username , displayName , timezone , location , langTag , avatarUrl , metadata );
} catch ( error ) {
// handle error
}
Authenticate
# authenticateApple
# Authenticate user and create a session token using an Apple sign in token.
Parameters Name Default Description token
string
REQUIRED Apple sign in token. username
string The user's username. If left empty, one is generated. create
bool true Create user if one didn't exist previously. Returns Name Description userID
string The user ID of the authenticated user. username
string The username of the authenticated user. create
bool Value indicating if this account was just created or already existed. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime . AuthResult ;
try {
result = nk . authenticateApple ( 'some-oauth-access-token' , 'username' , true );
} catch ( error ) {
// Handle error
}
authenticateCustom
# Authenticate user and create a session token using a custom authentication managed by an external service or source not already supported by Nakama.
Parameters Name Default Description id
string
REQUIRED Custom ID to use to authenticate the user. Must be between 6-128 characters. username
string The user's username. If left empty, one is generated. create
bool true Create user if one didn't exist previously. Returns Name Description userID
string The user ID of the authenticated user. username
string The username of the authenticated user. create
bool Value indicating if this account was just created or already existed. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime . AuthResult ;
try {
result = nk . authenticateCustom ( '48656C6C6F20776F726C64' , 'username' , true );
} catch ( error ) {
// Handle error
}
authenticateDevice
# Authenticate user and create a session token using a device identifier.
Parameters Name Default Description id
string
REQUIRED Device ID to use to authenticate the user. Must be between 1-128 characters. username
string The user's username. If left empty, one is generated. create
bool true Create user if one didn't exist previously. Returns Name Description userID
string The user ID of the authenticated user. username
string The username of the authenticated user. create
bool Value indicating if this account was just created or already existed. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime . AuthResult ;
try {
result = nk . authenticateDevice ( '48656C6C6F20776F726C64' , 'username' , true );
} catch ( error ) {
// Handle error
}
authenticateEmail
# Authenticate user and create a session token using an email address and password.
Parameters Name Default Description email
string
REQUIRED Email address to use to authenticate the user. Must be between 10-255 characters. password
string
REQUIRED Password to set. Must be longer than 8 characters. username
string The user's username. If left empty, one is generated. create
bool true Create user if one didn't exist previously. Returns Name Description userID
string The user ID of the authenticated user. username
string The username of the authenticated user. create
bool Value indicating if this account was just created or already existed. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime . AuthResult ;
try {
result = nk . authenticateEmail ( 'email@example.com' , 'password' , 'username' , true );
} catch ( error ) {
// Handle error
}
authenticateFacebook
# Authenticate user and create a session token using a Facebook account token.
Parameters Name Default Description token
string
REQUIRED Facebook OAuth or Limited Login (JWT) access token. import
bool true Whether to automatically import Facebook friends after authentication. username
string The user's username. If left empty, one is generated. create
bool true Create user if one didn't exist previously. Returns Name Description userID
string The user ID of the authenticated user. username
string The username of the authenticated user. create
bool Value indicating if this account was just created or already existed. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime . AuthResult ;
try {
result = nk . authenticateFacebook ( 'some-oauth-access-token' , 'username' , true );
} catch ( error ) {
// Handle error
}
authenticateFacebookInstantGame
# Authenticate user and create a session token using a Facebook Instant Game.
Parameters Name Default Description playerInfo
string
REQUIRED Facebook Player info. username
string The user's username. If left empty, one is generated. create
bool true Create user if one didn't exist previously. Returns Name Description userID
string The user ID of the authenticated user. username
string The username of the authenticated user. create
bool Value indicating if this account was just created or already existed. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime . AuthResult ;
try {
result = nk . authenticateFacebookInstantGame ( 'player-info' , 'username' , true );
} catch ( error ) {
// Handle error
}
authenticateGameCenter
# Authenticate user and create a session token using Apple Game Center credentials.
Parameters Name Default Description playerId
string
REQUIRED PlayerId provided by GameCenter. bundleId
string
REQUIRED BundleId of your app on iTunesConnect. timestamp
int
REQUIRED Timestamp at which Game Center authenticated the client and issued a signature. salt
string
REQUIRED A random string returned by Game Center authentication on client. signature
string
REQUIRED A signature returned by Game Center authentication on client. publicKeyUrl
string
REQUIRED A URL to the public key returned by Game Center authentication on client. username
string The user's username. If left empty, one is generated. create
bool true Create user if one didn't exist previously. Returns Name Description userID
string The user ID of the authenticated user. username
string The username of the authenticated user. create
bool Value indicating if this account was just created or already existed. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let result = {} as nkruntime . AuthResult ;
try {
// Example assumes arguments are defined.
result = nk . authenticateGameCenter ( playerId , bundleId , timestamp , salt , signature , publicKeyUrl , username , create );
} catch ( error ) {
// Handle error
}
authenticateGoogle
# Authenticate user and create a session token using a Google ID token.
Parameters Name Default Description token
string
REQUIRED Google OAuth access token. username
string The user's username. If left empty, one is generated. create
bool true Create user if one didn't exist previously. Returns Name Description userID
string The user ID of the authenticated user. username
string The username of the authenticated user. create
bool Value indicating if this account was just created or already existed. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime . AuthResult ;
try {
result = nk . authenticateGoogle ( 'some-id-token' , 'username' , true );
} catch ( error ) {
// Handle error
}
authenticateSteam
# Authenticate user and create a session token using a Steam account token.
Parameters Name Default Description token
string
REQUIRED Steam token. username
string The user's username. If left empty, one is generated. import
bool true Whether to automatically import Steam friends after authentication. create
bool true Create user if one didn't exist previously. Returns Name Description userID
string The user ID of the authenticated user. username
string The username of the authenticated user. create
bool Value indicating if this account was just created or already existed. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime . AuthResult ;
try {
result = nk . authenticateSteam ( 'steam-token' , 'username' , true );
} catch ( error ) {
// Handle error
}
authenticateTokenGenerate
# Generate a Nakama session token from a user ID.
Parameters Name Default Description userId
string
REQUIRED User ID to use to generate the token. username
string The user's username. If left empty, one is generated. expiresAt
number UTC time in seconds when the token must expire. Defaults to server configured expiry time. vars
Extra information that will be bundled in the session token. Returns Name Description token
string The Nakama session token. validity
number The period for which the token remains valid. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result = {} as nkruntime . TokenGenerateResult ;
try {
result = nk . authenticateTokenGenerate ( 'steam-token' , 'username' , true );
} catch ( error ) {
// Handle error
}
linkApple
# Link Apple authentication to a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be linked. token
string
REQUIRED Apple sign in token. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>' ;
let token = '<Token>' ;
try {
nk . linkApple ( userId , token );
} catch ( error ) {
// Handle error
}
linkCustom
# Link custom authentication to a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be linked. customId
string
REQUIRED Custom ID to be linked to the user. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>' ;
let customId = '<CustomId>' ;
try {
nk . linkCustom ( userId , customId );
} catch ( error ) {
// Handle error
}
linkDevice
# Link device authentication to a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be linked. deviceId
string
REQUIRED Device ID to be linked to the user. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>' ;
let deviceId = '<Deviceid>' ;
try {
nk . linkDevice ( userId , deviceId );
} catch ( error ) {
// Handle error
}
linkEmail
# Link email authentication to a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be linked. email
string
REQUIRED Authentication email to be linked to the user. password
string
REQUIRED Password to set. Must be longer than 8 characters. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let userId = '<UserId>' ;
let email = 'test@heroiclabs.com' ;
let password = 'correct horse battery staple'
try {
nk . linkEmail ( userId , email , password );
} catch ( error ) {
// Handle error
}
linkFacebook
# Link Facebook authentication to a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be linked. username
string If left empty, one is generated. token
string
REQUIRED Facebook OAuth or Limited Login (JWT) access token. importFriends
bool true Whether to automatically import Facebook friends after authentication. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
let userId = '<UserId>' ;
let username = '<Username>' ;
let token = '<Token>' ;
let importFriends = true ;
try {
nk . linkFacebook ( userId , username , token , importFriends );
} catch ( error ) {
// Handle error
}
linkFacebookInstantGame
# Link Facebook Instant Game authentication to a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be linked. playerInfo
string
REQUIRED Facebook player info. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>' ;
let signedPlayerInfo = '<SignedPlayerInfo>' ;
try {
nk . linkFacebookInstantGame ( userId , signedPlayerInfo );
} catch ( error ) {
// Handle error
}
linkGameCenter
# Link Apple Game Center authentication to a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be linked. playerId
string
REQUIRED Player ID provided by Game Center. bundleId
string
REQUIRED Bundle ID of your app on iTunesConnect. timestamp
int
REQUIRED Timestamp at which Game Center authenticated the client and issued a signature. salt
string
REQUIRED A random string returned by Game Center authentication on client. signature
string
REQUIRED A signature returned by Game Center authentication on client. publicKeyUrl
string
REQUIRED A URL to the public key returned by Game Center authentication on client. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
let userId = '<UserId>' ;
let playerId = '<PlayerId>' ;
let bundleId = '<BundleId>' ;
let timestamp = 0 ;
let salt = "<Salt>" ;
let signature = "<Signature>" ;
let publicKeyUrl = "<PublicKeyUrl>" ;
try {
nk . linkGameCenter ( userId , playerId , bundleId , timestamp , salt , signature , publicKeyUrl );
} catch ( error ) {
// Handle error
}
linkGoogle
# Link Google authentication to a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be linked. token
string
REQUIRED Google OAuth access token. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>' ;
let token = '<Token>' ;
try {
nk . linkGoogle ( userId , token );
} catch ( error ) {
// Handle error
}
linkSteam
# Link Steam authentication to a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be linked. username
string If left empty, one is generated. token
string
REQUIRED Steam access token. importFriends
bool true Whether to automatically import Steam friends after authentication. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
let userId = '<UserId>' ;
let username = '<Username>' ;
let token = '<Token>' ;
let importFriends = true ;
try {
nk . linkSteam ( userId , username , token , importFriends );
} catch ( error ) {
// Handle error
}
unlinkApple
# Unlink Apple authentication from a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be unlinked. token
string
REQUIRED Apple sign in token. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>' ;
let token = '<Token>' ;
try {
nk . unlinkApple ( userId , token );
} catch ( error ) {
// Handle error
}
unlinkCustom
# Unlink custom authentication from a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be unlinked. customId
string Custom ID to be unlinked from the user. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>' ;
let customId = '<CustomId>' ;
try {
nk . unlinkCustom ( userId , customId );
} catch ( error ) {
// Handle error
}
unlinkDevice
# Unlink device authentication from a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be unlinked. deviceId
string
REQUIRED Device ID to be unlinked to the user. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>' ;
let deviceId = '<Deviceid>' ;
try {
nk . unlinkDevice ( userId , deviceId );
} catch ( error ) {
// Handle error
}
unlinkEmail
# Unlink email authentication from a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be unlinked. email
string Email to be unlinked from the user. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>' ;
let email = 'test@heroiclabs.com' ;
try {
nk . unlinkEmail ( userId , email );
} catch ( error ) {
// Handle error
}
unlinkFacebook
# Unlink Facebook authentication from a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be unlinked. token
string Facebook OAuth or Limited Login (JWT) access token. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>' ;
let token = '<Token>' ;
try {
nk . unlinkFacebook ( userId , token );
} catch ( error ) {
// Handle error
}
unlinkFacebookInstantGame
# Unlink Facebook Instant Game authentication from a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be unlinked. playerInfo
string Facebook player info. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>' ;
let signedPlayerInfo = '<SignedPlayerInfo>' ;
try {
nk . unlinkFacebookInstantGame ( userId , signedPlayerInfo );
} catch ( error ) {
// Handle error
}
unlinkGameCenter
# Unlink Apple Game Center authentication from a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be unlinked. playerId
string
REQUIRED Player ID provided by Game Center. bundleId
string
REQUIRED Bundle ID of your app on iTunesConnect. timestamp
int
REQUIRED Timestamp at which Game Center authenticated the client and issued a signature. salt
string
REQUIRED A random string returned by Game Center authentication on client. signature
string
REQUIRED A signature returned by Game Center authentication on client. publicKeyUrl
string
REQUIRED A URL to the public key returned by Game Center authentication on client. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
let userId = '<UserId>' ;
let playerId = '<PlayerId>' ;
let bundleId = '<BundleId>' ;
let timestamp = 0 ;
let salt = "<Salt>" ;
let signature = "<Signature>" ;
let publicKeyUrl = "<PublicKeyUrl>" ;
try {
nk . unlinkGameCenter ( userId , playerId , bundleId , timestamp , salt , signature , publicKeyUrl );
} catch ( error ) {
// Handle error
}
unlinkGoogle
# Unlink Google authentication from a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be unlinked. token
string Google OAuth access token. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>' ;
let token = '<Token>' ;
try {
nk . unlinkGoogle ( userId , token );
} catch ( error ) {
// Handle error
}
unlinkSteam
# Unlink Steam authentication from a user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be unlinked. token
string Steam access token. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '<UserId>' ;
let token = '<Token>' ;
try {
nk . unlinkSteam ( userId , token );
} catch ( error ) {
// Handle error
}
Chat
# channelIdBuild
# Create a channel identifier to be used in other runtime calls. Does not create a channel.
Parameters Name Default Description senderId
string
REQUIRED UserID of the message sender (when applicable). Defaults to the system user if void. target
string
REQUIRED Can be the room name, group identifier, or another username. chanType
nkruntime.ChannelType
REQUIRED The type of channel, either Room (1), Direct (2), or Group (3). Returns Name Description channelId
string The generated ID representing a channel. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result : string ;
try {
result = nk . channelIdBuild ( '<SenderId>' , '<RoomName>' , nkruntime . ChannelType . Room );
} catch ( error ) {
// Handle error
}
channelMessageRemove
# Remove a message on a realtime chat channel.
Parameters Name Default Description channelId
string
REQUIRED The ID of the channel to send the message on. messageId
string
REQUIRED The ID of the message to remove. senderId
string
REQUIRED The UUID for the sender of this message. If left empty, it will be assumed that it is a system message. senderUsername
string
REQUIRED The username of the user to send this message as. If left empty, it will be assumed that it is a system message. persist
bool true Whether to record this message in the channel history. Returns Name Description channelMessageRemove
nkruntime.ChannelMessageAck Message removed ack containing the following variables: 'channelId', 'messageId', 'code', 'username', 'createTime', 'updateTime', and 'persistent'. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
let result : nkruntime.ChannelMessageAck ;
let channelId = '<ChannelId>' ;
let messageId = '<MessageId>' ;
let senderId = '<SenderId>' ;
let senderUsername = 'Someone' ;
let persist = true ;
try {
result = nk . channelMessageRemove ( channelId , messageId , senderId , senderUsername , persist );
} catch ( error ) {
// Handle error
}
channelMessageSend
# Send a message on a realtime chat channel.
Parameters Name Default Description channelId
string
REQUIRED The ID of the channel to send the message on. content
object
REQUIRED Message content. senderId
string
REQUIRED The UUID for the sender of this message. If left empty, it will be assumed that it is a system message. senderUsername
string
REQUIRED The username of the user to send this message as. If left empty, it will be assumed that it is a system message. persist
bool true Whether to record this message in the channel history. Returns Name Description channelMessageSend
nkruntime.ChannelMessageAck Message sent ack containing the following variables: 'channelId', 'messageId', 'code', 'username', 'createTime', 'updateTime', and 'persistent'. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
let result : nkruntime.ChannelMessageSendAck ;
let channelId = '<ChannelId>' ;
let content = { message : 'Hello world' };
let senderId = '<SenderId>' ;
let senderUsername = 'Someone' ;
let persist = true ;
try {
result = nk . channelMessageSend ( channelId , content , senderId , senderUsername , persist );
} catch ( error ) {
// Handle error
}
channelMessagesList
# List messages from a realtime chat channel.
Parameters Name Default Description channelId
string
REQUIRED The ID of the channel to list messages from. limit
number 100 The number of messages to return per page. forward
bool true Whether to list messages from oldest to newest, or newest to oldest. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. Returns Name Description channelMessagesList
nkruntime.ChannelMessageList Messages from the specified channel and possibly a cursor. If cursor is empty/null there are no further results. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let messages = {} as nkruntime . ChannelMessageList ;
try {
let channelId = "<channelId>" ;
messages = nk . channelMessagesList ( channelId );
} catch ( error ) {
// Handle error
}
channelMessageUpdate
# Update a message on a realtime chat channel.
Parameters Name Default Description channelId
string
REQUIRED The ID of the channel to send the message on. messageId
string
REQUIRED The ID of the message to update. content
object
REQUIRED Message content. senderId
string
REQUIRED The UUID for the sender of this message. If left empty, it will be assumed that it is a system message. senderUsername
string
REQUIRED The username of the user to send this message as. If left empty, it will be assumed that it is a system message. persist
bool true Whether to record this message in the channel history. Returns Name Description channelMessageUpdate
nkruntime.ChannelMessageAck Message updated ack containing the following variables: 'channelId', 'messageId', 'code', 'username', 'createTime', 'updateTime', and 'persistent'. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
let result : nkruntime.ChannelMessageSendAck ;
let channelId = '<ChannelId>' ;
let messageId = '<MessageId>' ;
let content = { message : 'Hello another world' };
let senderId = '<SenderId>' ;
let senderUsername = 'Someone' ;
let persist = true ;
try {
result = nk . channelMessageUpdate ( channelId , messageId , content , senderId , senderUsername , persist );
} catch ( error ) {
// Handle error
}
Events
# event
# Generate an event.
Parameters Name Default Description event_name
string
REQUIRED The name of the event to be created. properties
[]string
REQUIRED An array of event properties. ts
int Timestamp for when event is created. external
bool false Whether the event is external. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
let eventName = '<EventName>' ;
let properties = [ 'properties' ];
let timestamp = 0 ;
let external = true ;
try {
nk . event ( eventName , properties , timestamp , external );
} catch ( error ) {
// Handle error
}
Friends
# friendsAdd
# Add friends to a user.
Parameters Name Default Description userId
string
REQUIRED The ID of the user to whom you want to add friends. username
string
REQUIRED The name of the user to whom you want to add friends. ids
[]string
REQUIRED Table array of IDs of the users you want to add as friends. usernames
[]string
REQUIRED Table array of usernames of the users you want to add as friends. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
let userId = "b1aafe16-7540-11e7-9738-13777fcc7cd8" ;
let username = "username" ;
let userIds = [ '9a51cf3a-2377-11eb-b713-e7d403afe081' , 'a042c19c-2377-11eb-b7c1-cfafae11cfbc' ];
let usernames = [ "newfriend1" , "newfriend2" ];
try {
nk . friendsAdd ( userId , username , userIds , usernames );
} catch ( error ) {
// Handle error
}
friendsBlock
# Block friends for a user.
Parameters Name Default Description userId
string
REQUIRED The ID of the user for whom you want to block friends. username
string
REQUIRED The name of the user for whom you want to block friends. ids
[]string
REQUIRED Table array of IDs of the users you want to block as friends. usernames
[]string
REQUIRED Table array of usernames of the users you want to block as friends. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
let userId = "b1aafe16-7540-11e7-9738-13777fcc7cd8" ;
let username = "username" ;
let userIds = [ '9a51cf3a-2377-11eb-b713-e7d403afe081' , 'a042c19c-2377-11eb-b7c1-cfafae11cfbc' ];
let usernames = [ "exfriend1" , "exfriend2" ];
try {
nk . friendsBlock ( userId , username , userIds , usernames );
} catch ( error ) {
// Handle error
}
friendsDelete
# Delete friends from a user.
Parameters Name Default Description userId
string
REQUIRED The ID of the user from whom you want to delete friends. username
string
REQUIRED The name of the user from whom you want to delete friends. ids
[]string
REQUIRED Table array of IDs of the users you want to delete as friends. usernames
[]string
REQUIRED Table array of usernames of the users you want to delete as friends. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
let userId = "b1aafe16-7540-11e7-9738-13777fcc7cd8" ;
let username = "username" ;
let userIds = [ '9a51cf3a-2377-11eb-b713-e7d403afe081' , 'a042c19c-2377-11eb-b7c1-cfafae11cfbc' ];
let usernames = [ "exfriend1" , "exfriend2" ];
try {
nk . friendsDelete ( userId , username , userIds , usernames );
} catch ( error ) {
// Handle error
}
friendsList
# List all friends, invites, invited, and blocked which belong to a user.
Parameters Name Default Description userId
string
REQUIRED The ID of the user whose friends, invites, invited, and blocked you want to list. limit
number 100 The number of friends to retrieve in this page of results. No more than 100 limit allowed per result. state
number The state of the friendship with the user. If unspecified this returns friends in all states for the user. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. Returns Name Description friends
nkruntime.FriendList The user information for users that are friends of the current user. cursor
string An optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or null when fetching last available page. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
let friends = {} as nkruntime . FriendList ;
try {
let userId = 'b1aafe16-7540-11e7-9738-13777fcc7cd8' ;
let limit = 100 ;
let state = 0 ;
friends = nk . friendsList ( userId , limit , state );
} catch ( error ) {
// Handle error
}
friendsOfFriendsList
# List all friends of friends of a user.
Parameters Name Default Description userId
string
REQUIRED The ID of the user whose friends of friends you want to list. limit
number 10 The number of friends to retrieve in this page of results. No more than 100 limit allowed per result. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. Returns Name Description friends
nkruntime.FriendsOfFriendsList The user information for users that are friends of friends of the current user. cursor
string An optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or null when fetching last available page. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let friends = {} as nkruntime . FriendList ;
try {
let userId = "b1aafe16-7540-11e7-9738-13777fcc7cd8" ;
let limit = 100 ;
friends = nk . friendsOfFriendsList ( userId , limit );
} catch ( error ) {
// Handle error
}
Groups
# groupCreate
# Setup a group with various configuration settings. The group will be created if they don't exist or fail if the group name is taken.
Parameters Name Default Description userId
string
REQUIRED The user ID to be associated as the group superadmin. name
string
REQUIRED Group name, must be unique. creatorId
string The user ID to be associated as creator. If not set or nil/null, system user will be set. langTag
string Group language. description
string Group description, can be left empty as nil/null. avatarUrl
string URL to the group avatar, can be left empty as nil/null. open
bool false Whether the group is for anyone to join, or members will need to send invitations to join. metadata
object Custom information to store for this group. Can be left empty as nil/null. maxCount
number 100 Maximum number of members to have in the group. Returns Name Description createGroup
nkruntime.Group The groupId of the newly created group. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let userId = 'dcb891ea-a311-4681-9213-6741351c9994' ;
let creatorId = 'dcb891ea-a311-4681-9213-6741351c9994' ;
let name = 'Some unique group name' ;
let description = 'My awesome group.' ;
let lang = 'en' ;
let open = true ;
let avatarURL = 'url://somelink' ;
let metadata = { custom_field : 'some_value' };
let maxCount = 100 ;
let group = {} as nkruntime . Group ;
try {
group = nk . groupCreate ( userId , name , creatorId , lang , description , avatarURL , open , metadata , maxCount );
} catch ( error ) {
// Handle error
}
groupDelete
# Delete a group.
Parameters Name Default Description groupId
string
REQUIRED The ID of the group to delete. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
try {
nk . groupDelete ( 'f00fa79a-750f-11e7-8626-0fb79f45ff97' );
} catch ( error ) {
// Handle error
}
groupsGetId
# Fetch one or more groups by their ID.
Parameters Name Default Description groupIds
string[]
REQUIRED An array of strings of the IDs for the groups to get. Returns Name Description getGroups
nkruntime.Group[] An array of groups with their fields. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let groups : nkruntime.Group [];
try {
let groupIds = [ 'dcb891ea-a311-4681-9213-6741351c9994' ];
groups = nk . groupsGetId ( groupIds );
} catch ( error ) {
// Handle error
}
groupsGetRandom
# Fetch one or more groups randomly.
Parameters Name Default Description count
number
REQUIRED The number of groups to fetch. Returns Name Description groups
nkruntime.Group[] A list of group record objects. error
error An optional error value if an error occurred.
groupsList
# Find groups based on the entered criteria.
Parameters Name Default Description name
string
REQUIRED Search for groups that contain this value in their name. langTag
string Filter based upon the entered language tag. members
number Search by number of group members. open
bool Filter based on whether groups are Open or Closed. limit
number 100 Return only the required number of groups denoted by this limit value. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. Returns Name Description groups
nkruntime.GroupList A list of groups. cursor
string An optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or null when fetching last available page. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
let groupName = "Heroic" ;
let langTag = "en" ;
let members = 10 ;
let open = true ;
let limit = 100 ;
let results : nkruntime.GroupList = {};
try {
results = nk . groupsList ( groupName , langTag , open , members , limit );
} catch ( error ) {
// Handle error
}
groupUpdate
# Update a group with various configuration settings. The group which is updated can change some or all of its fields.
Parameters Name Default Description groupId
string
REQUIRED The ID of the group to update. userId
string
REQUIRED User ID calling the update operation for permission checking. Set as nil to enact the changes as the system user. name
string Group name, can be empty if not changed. creatorId
string The user ID to be associated as creator. Can be empty if not changed. langTag
string Group language. Empty if not updated. description
string Group description, can be left empty if not updated. avatarUrl
string URL to the group avatar, can be left empty if not updated. open
bool Whether the group is for anyone to join or not. metadata
object Custom information to store for this group. Use nil if field is not being updated. maxCount
number Maximum number of members to have in the group. Use 0, nil/null if field is not being updated. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let metadata = { someField : 'some value' };
let groupId = 'f00fa79a-750f-11e7-8626-0fb79f45ff97' ;
let description = 'An updated description' ;
try {
nk . groupUpdate ( groupId , null , null , null , null , description , null , true , metadata );
} catch ( error ) {
// Handle error.
}
groupUserJoin
# Join a group for a particular user.
Parameters Name Default Description groupId
string
REQUIRED The ID of the group to join. userId
string
REQUIRED The user ID to add to this group. username
string
REQUIRED The username of the user to add to this group. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994' ;
let userId = '9a51cf3a-2377-11eb-b713-e7d403afe081' ;
let username = 'myusername' ;
try {
nk . groupUserJoin ( groupId , userId , username );
} catch ( error ) {
// Handle error
}
groupUserLeave
# Leave a group for a particular user.
Parameters Name Default Description groupId
string
REQUIRED The ID of the group to leave. userId
string
REQUIRED The user ID to remove from this group. username
string
REQUIRED The username of the user to remove from this group. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994' ;
let userId = '9a51cf3a-2377-11eb-b713-e7d403afe081' ;
let username = 'myusername' ;
try {
nk . groupUserLeave ( groupId , userId , username );
} catch ( error ) {
// Handle error
}
groupUsersAdd
# Add users to a group.
Parameters Name Default Description groupId
string
REQUIRED The ID of the group to add users to. userIds
string[]
REQUIRED Table array of user IDs to add to this group. callerId
string User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permission checks are bypassed. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994' ;
let userIds = [ '9a51cf3a-2377-11eb-b713-e7d403afe081' , 'a042c19c-2377-11eb-b7c1-cfafae11cfbc' ];
try {
nk . groupUsersAdd ( groupId , userIds );
} catch ( error ) {
// Handle error
}
groupUsersBan
# Ban users from a group.
Parameters Name Default Description groupId
REQUIRED The ID of the group to ban users from. userIds
REQUIRED Table array of user IDs to ban from this group. callerId
string User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permission checks are bypassed. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994' ;
let userIds = [ '9a51cf3a-2377-11eb-b713-e7d403afe081' , 'a042c19c-2377-11eb-b7c1-cfafae11cfbc' ];
let callerId = '6ffededc-bfec-4ea1-a070-274a05825a47' ;
try {
nk . groupUsersBan ( groupId , userIds , callerId );
} catch ( error ) {
// Handle error
}
groupUsersDemote
# Demote users in a group.
Parameters Name Default Description groupId
string
REQUIRED The ID of the group whose members are being demoted. userIds
string[]
REQUIRED Table array of user IDs to demote. callerId
string User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permission checks are bypassed. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994' ;
let userIds = [ '9a51cf3a-2377-11eb-b713-e7d403afe081' , 'a042c19c-2377-11eb-b7c1-cfafae11cfbc' ];
try {
nk . groupUsersDemote ( groupId , userIds );
} catch ( error ) {
// Handle error
}
groupUsersKick
# Kick users from a group.
Parameters Name Default Description groupId
string
REQUIRED The ID of the group to kick users from. userIds
string[]
REQUIRED Table array of user IDs to kick. callerId
string User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permission checks are bypassed. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994' ;
let userIds = [ '9a51cf3a-2377-11eb-b713-e7d403afe081' , 'a042c19c-2377-11eb-b7c1-cfafae11cfbc' ];
try {
nk . groupUsersKick ( groupId , userIds );
} catch ( error ) {
// Handle error
}
groupUsersList
# List all members, admins and superadmins which belong to a group. This also list incoming join requests.
Parameters Name Default Description groupId
string
REQUIRED The ID of the group to list members for. limit
int 100 The maximum number of entries in the listing. state
int null The state of the user within the group. If unspecified this returns users in all states. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. Returns Name Description groupUsers
nkruntime.GroupUserList The user information for members, admins and superadmins for the group. Also users who sent a join request. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994' ;
let groupUsers = {} as nkruntime . GroupUserList ;
try {
groupUsers = nk . groupUsersList ( groupId );
} catch ( error ) {
// Handle error
}
Promote users in a group.
Parameters Name Default Description groupId
string
REQUIRED The ID of the group whose members are being promoted. userIds
string[]
REQUIRED Table array of user IDs to promote. callerId
string User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permission checks are bypassed. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let groupId = 'dcb891ea-a311-4681-9213-6741351c9994' ;
let userIds = [ '9a51cf3a-2377-11eb-b713-e7d403afe081' , 'a042c19c-2377-11eb-b7c1-cfafae11cfbc' ];
try {
nk . groupUsersPromote ( groupId , userIds );
} catch ( error ) {
// Handle error
}
userGroupsList
# List all groups which a user belongs to and whether they've been accepted or if it's an invite.
Parameters Name Default Description userId
string
REQUIRED The ID of the user to list groups for. Returns Name Description userGroups
nkruntime.UserGroupList A table of groups with their fields. cursor
string An optional next page cursor that can be used to retrieve the next page of records (if any). error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '64ef6cb0-7512-11e7-9e52-d7789d80b70b' ;
let groups : nkruntime.UserGroupList ;
try {
groups = nk . userGroupsList ( userId );
} catch ( error ) {
// Handle error
}
Leaderboards
# leaderboardCreate
# Setup a new dynamic leaderboard with the specified ID and various configuration settings. The leaderboard will be created if it doesn't already exist, otherwise its configuration will not be updated.
Parameters Name Default Description leaderboardID
string
REQUIRED The unique identifier for the new leaderboard. This is used by clients to submit scores. authoritative
bool false Mark the leaderboard as authoritative which ensures updates can only be made via the Go runtime. No client can submit a score directly. sortOrder
string The sort order for records in the leaderboard. Possible values are "asc" or "desc". operator
string The operator that determines how scores behave when submitted. Possible values are "best", "set", or "incr". resetSchedule
string The cron format used to define the reset schedule for the leaderboard. This controls when a leaderboard is reset and can be used to power daily/weekly/monthly leaderboards. metadata
object The metadata you want associated to the leaderboard. Some good examples are weather conditions for a racing game. enableRanks
bool false Whether to enable rank values for the leaderboard. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let authoritative = false ;
let sort = nkruntime . SortOrder . DESCENDING ;
let operator = nkruntime . Operator . BEST ;
let reset = '0 0 * * 1' ;
let metadata = {
weatherConditions : 'rain' ,
};
let enableRanks = true // Set to true to enable rank computation on leaderboard records.
try {
nk . leaderboardCreate ( id , authoritative , sort , operator , reset , metadata , enableRanks );
} catch ( error ) {
// Handle error
}
leaderboardDelete
# Delete a leaderboard and all scores that belong to it.
Parameters Name Default Description id
string
REQUIRED The unique identifier for the leaderboard to delete. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
try {
nk . leaderboardDelete ( id );
} catch ( error ) {
// Handle error
}
leaderboardList
# Find leaderboards which have been created on the server. Leaderboards can be filtered with categories.
Parameters Name Default Description limit
number 10 Return only the required number of leaderboards denoted by this limit value. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. Returns Name Description leaderboardList
nkruntime.LeaderboardList[] A list of leaderboard results and possibly a cursor. If cursor is empty/null there are no further results. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let limit = 100 ; // Number to list per page.
let results : nkruntime.LeaderboardList = {};
try {
results = nk . leaderboardList ( limit );
} catch ( error ) {
// Handle error
}
leaderboardRanksDisable
# Disable a leaderboard rank cache freeing its allocated resources. If already disabled is a NOOP.
Parameters Name Default Description id
string
REQUIRED The leaderboard id. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
try {
nk . leaderboardRanksDisable ( id );
} catch ( error ) {
// Handle error
}
leaderboardRecordDelete
# Remove an owner's record from a leaderboard, if one exists.
Parameters Name Default Description id
string
REQUIRED The unique identifier for the leaderboard to delete from. owner
string
REQUIRED The owner of the score to delete. Mandatory field. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let owner = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
try {
nk . leaderboardRecordDelete ( id , owner );
} catch ( error ) {
// Handle error
}
leaderboardRecordsHaystack
# Fetch the list of leaderboard records around the owner.
Parameters Name Default Description id
string
REQUIRED The unique identifier for the leaderboard. owner
string
REQUIRED The owner of the score to list records around. Mandatory field. limit
number
REQUIRED Return only the required number of leaderboard records denoted by this limit value. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. overrideExpiry
number 0 Optionally retrieve records from previous resets by specifying the reset point in time in UTC seconds. Must be equal or greater than 0. Returns Name Description records
nkruntime.LeaderboardRecordList The leaderboard records according to ID and possibly a cursor. If cursor is empty/null there are no further results. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let owner = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
let limit = 10 ;
let overrideExpiry = 3600 ;
let results : nkruntime.Leaderboard [] = [];
try {
results = nk . leaderboardRecordsHaystack ( id , owner , limit , overrideExpiry );
} catch ( error ) {
// Handle error
}
leaderboardRecordsList
# List records on the specified leaderboard, optionally filtering to only a subset of records by their owners. Records will be listed in the preconfigured leaderboard sort order.
Parameters Name Default Description id
string
REQUIRED The unique identifier for the leaderboard to list. Mandatory field. owners
string[]
REQUIRED Array of owners to filter to. limit
number
REQUIRED The maximum number of records to return (Max 10,000). cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. overrideExpiry
int Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0. Returns Name Description records
nkruntime.LeaderboardRecord[] A page of leaderboard records. ownerRecords
nkruntime.LeaderboardRecord[] A list of owner leaderboard records (empty if the owners input parameter is not set). nextCursor
string An optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or null when fetching last available page. prevCursor
string An optional previous page cursor that can be used to retrieve the previous page of records (if any). error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
let result : nkruntime.LeaderboardRecordList ;
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let ownerIds : string [] = [];
let limit = 100 ;
let cursor = '' ;
let overrideExpiry = 3600 ;
try {
result = nk . leaderboardRecordsList ( id , ownerIds , limit , cursor , overrideExpiry );
} catch ( error ) {
// Handle error
}
leaderboardRecordsListCursorFromRank
# Build a cursor to be used with leaderboardRecordsList to fetch records starting at a given rank. Only available if rank cache is not disabled for the leaderboard.
Parameters Name Default Description leaderboardID
string
REQUIRED The unique identifier of the leaderboard. rank
number
REQUIRED The rank to start listing leaderboard records from. overrideExpiry
number Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0. Returns Name Description leaderboardListCursor
string A string cursor to be used with leaderboardRecordsList. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let rank = 1 ;
let overrideExpiry = 3600 ;
try {
result = nk . leaderboardRecordsListCursorFromRank ( id , rank , overrideExpiry );
} catch ( error ) {
// Handle error
}
leaderboardRecordWrite
# Use the preconfigured operator for the given leaderboard to submit a score for a particular user.
Parameters Name Default Description id
string
REQUIRED The unique identifier for the leaderboard to submit to. owner
string
REQUIRED The owner of this score submission. username
string The owner username of this score submission, if it's a user. score
number 0 The score to submit. subscore
number 0 A secondary subscore parameter for the submission. metadata
object The metadata you want associated to this submission. Some good examples are weather conditions for a racing game. Returns Name Description record
nkruntime.LeaderboardRecord The newly created leaderboard record. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let ownerID = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
let username = '02ebb2c8' ;
let score = 10 ;
let subscore = 0 ;
let metadata = {
weatherConditions : 'rain' ,
};
let result : nkruntime.LeaderboardRecord ;
try {
result = nk . leaderboardRecordWrite ( id , ownerID , username , score , subscore , metadata );
} catch ( error ) {
// Handle error
}
leaderboardsGetId
# Fetch one or more leaderboards by ID.
Parameters Name Default Description ids
string[]
REQUIRED The array of leaderboard ids. Returns Name Description leaderboards
nkruntime.Leaderboard[] The leaderboard records according to ID. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
let leaderboardIds = [
'3ea5608a-43c3-11e7-90f9-7b9397165f34' ,
'447524be-43c3-11e7-af09-3f7172f05936' ,
]
let leaderboards : nkruntime.Leaderboard [];
try {
leaderboards = nk . leaderboardsGetId ( leaderboardIds );
} catch ( error ) {
// Handle error
}
Matches
# matchCreate
# Create a new authoritative realtime multiplayer match running on the given runtime module name. The given params are passed to the match's init hook.
Parameters Name Default Description module
string
REQUIRED The name of an available runtime module that will be responsible for the match. This was registered in InitModule. params
Any value to pass to the match init hook. Returns Name Description matchId
string The match ID of the newly created match. Clients can immediately use this ID to join the match. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
let module = 'some.folder.module' ;
let params = {
some : 'data' ,
}
let matchId : string ;
try {
matchId = nk . matchCreate ( module , params );
} catch ( error ) {
// Handle error
}
matchGet
# Get information on a running match.
Parameters Name Default Description id
string
REQUIRED The ID of the match to fetch. Returns Name Description match
nkruntime.Match Information for the running match. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let matchId = '52f02f3e-5b48-11eb-b182-0f5058adfcc6' ;
let match : nkruntime.Match ;
try {
match = nk . matchGet ( matchId );
} catch ( error ) {
// Handle error
}
matchList
# List currently running realtime multiplayer matches and optionally filter them by authoritative mode, label, and current participant count.
Parameters Name Default Description limit
number 1 The maximum number of matches to list. authoritative
bool nil Set true to only return authoritative matches, false to only return relayed matches and nil to return both. label
string A label to filter authoritative matches by. Default "" meaning any label matches. minSize
number Inclusive lower limit of current match participants. maxSize
number Inclusive upper limit of current match participants. query
string Additional query parameters to shortlist matches. Returns Name Description match
nkruntime.Match[] A list of matches matching the parameters criteria. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
let limit = 10 ;
let isAuthoritative = false ;
let label = '' ;
let minSize = 2 ;
let maxSize = 4 ;
let matches : nkruntime.Match [] = [];
try {
matches = nk . matchList ( limit , isAuthoritative , label , minSize , maxSize );
} catch ( error ) {
// Handle error
}
matchSignal
# Allow the match handler to be sent a reservation signal to mark a user ID or session ID into the match state ahead of their join attempt and eventual join flow. Called when the match handler receives a runtime signal.
Parameters Name Default Description id
string
REQUIRED The user ID or session ID to send a reservation signal for. data
string
REQUIRED An arbitrary input supplied by the runtime caller of the signal. Returns Name Description data
string Arbitrary data to return to the runtime caller of the signal. May be a string or nil. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let matchId = '<MatchId>' ;
let data = '<Data>' ;
let result : string ;
try {
result = nk . matchSignal ( matchId , data );
} catch ( error ) {
// Handle error
}
Metrics
# metricsCounterAdd
# Add a custom metrics counter.
Parameters Name Default Description name
string
REQUIRED The name of the custom metrics counter. tags
map[string]string
REQUIRED The metrics tags associated with this counter. delta
number
REQUIRED An integer value to update this metric with. Returns Name Description
1
2
3
4
5
6
7
8
9
let name = "metricName" ;
let tags = new Map < string , string >(); // Metrics tags for this counter.
let delta = 100 ;
try {
nk . metricsCounterAdd ( name , tags , delta );
} catch ( error ) {
// handle error
}
metricsGaugeSet
# Add a custom metrics gauge.
Parameters Name Default Description name
string
REQUIRED The name of the custom metrics gauge. tags
map[string]string
REQUIRED The metrics tags associated with this gauge. value
number
REQUIRED A value to update this metric with. Returns Name Description
1
2
3
4
5
6
7
8
9
let name = "metricName" ;
let tags = new Map < string , string >(); // Metrics tags for this gauge.
let value = 3.14
try {
nk . metricsGaugeSet ( name , tags , value );
} catch ( error ) {
// handle error
}
metricsTimerRecord
# Add a custom metrics timer.
Parameters Name Default Description name
string
REQUIRED The name of the custom metrics timer. tags
map[string]string
REQUIRED The metrics tags associated with this timer. value
number
REQUIRED An integer value to update this metric with (in nanoseconds). Returns Name Description
1
2
3
4
5
6
7
8
9
let name = "metricName" ;
let tags = new Map < string , string >(); // Metrics tags for this gauge.
let value = 100000000000 ;
try {
nk . metricsTimerRecord ( name , tags , value )
} catch ( error ) {
// handle error
}
Notifications
# notificationsDelete
# Delete one or more in-app notifications.
Parameters Name Default Description notifications
any[]
REQUIRED A list of notifications to be deleted. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
let userId = "b1aafe16-7540-11e7-9738-13777fcc7cd8" ;
let notificationId = "9a51cf3a-2377-11eb-b713-e7d403afe081" ;
let notifications = [ userId = userId , notificationId = notificationId ];
try {
nk . notificationsDelete ( notifications );
} catch ( error ) {
// Handle error
}
notificationsDeleteId
# Delete notifications by their id.
Parameters Name Default Description ids
string[]
REQUIRED A list of notification ids. userID
string
REQUIRED Optional userID to scope deletions to that user only. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
let userId = "b1aafe16-7540-11e7-9738-13777fcc7cd8" ;
let notificationId = "9a51cf3a-2377-11eb-b713-e7d403afe081" ;
let notifications = [ notificationId ];
try {
nk . notificationsDeleteId ( notifications , userId );
} catch ( error ) {
// Handle error
}
notificationSend
# Send one in-app notification to a user.
Parameters Name Default Description userId
string
REQUIRED The user ID of the user to be sent the notification. subject
string
REQUIRED Notification subject. content
object
REQUIRED Notification content. Must be set but can be empty object. code
number
REQUIRED Notification code to use. Must be equal or greater than 0. sender
string The sender of this notification. If left empty, it will be assumed that it is a system notification. persistent
bool false Whether to record this in the database for later listing. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let receiverId = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
let subject = "You've unlocked level 100!" ;
let content = {
rewardCoins : 1000 ,
}
let code = 101 ;
let senderId = 'dcb891ea-a311-4681-9213-6741351c9994'
let persistent = true ;
try {
nk . notificationSend ( receiverId , subject , content , code , senderId , persistent );
} catch ( error ) {
// Handle error
}
notificationSendAll
# Send an in-app notification to all users.
Parameters Name Default Description subject
string
REQUIRED Notification subject. content
object
REQUIRED Notification content. Must be set but can be an empty object. code
number
REQUIRED Notification code to use. Must be greater than or equal to 0. persistent
bool false Whether to record this in the database for later listing. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
let subject = "You've unlocked level 100!" ;
let content = {
rewardCoins : 1000 ,
}
let code = 101 ;
let persistent = true ;
try {
nk . notificationSendAll ( subject , content , code , persistent );
} catch ( error ) {
// Handle error
}
notificationsGetId
# Get notifications by their id.
Parameters Name Default Description ids
string[]
REQUIRED A list of notification ids. userID
string
REQUIRED Optional userID to scope results to that user only. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
let userId = "b1aafe16-7540-11e7-9738-13777fcc7cd8" ;
let notificationId = "9a51cf3a-2377-11eb-b713-e7d403afe081" ;
let notifications = [ notificationId ];
try {
nk . notificationsGetId ( notifications , userId );
} catch ( error ) {
// Handle error
}
notificationsList
# List notifications by user id.
Parameters Name Default Description userID
string
REQUIRED Optional userID to scope results to that user only. limit
int
REQUIRED 100 Limit number of results. Must be a value between 1 and 1000. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. Returns Name Description notifications
nkruntime.NotificationList A list of notifications. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
let notifications = {} as nkruntime . NotificationList ;
let userId = "b1aafe16-7540-11e7-9738-13777fcc7cd8" ;
let limit = 20 ;
try {
notifications = nk . notificationsList ( userId , limit );
} catch ( error ) {
// Handle error
}
notificationsSend
# Send one or more in-app notifications to a user.
Parameters Name Default Description notifications
any[]
REQUIRED A list of notifications to be sent together. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let notifications : nkruntime.NotificationRequest [] = [
{
userId : '4c2ae592-b2a7-445e-98ec-697694478b1c' ,
subject : "You've unlocked level 100!" ,
content : { rewardCoins : 1000 },
code : 101 ,
persistent : true ,
},
{
userId : '69769447-b2a7-445e-98ec-8b1c4c2ae592' ,
subject : "You've unlocked level 100!" ,
content : { rewardCoins : 1000 },
code : 101 ,
persistent : true ,
},
];
try {
nk . notificationsSend ( notifications );
} catch ( error ) {
// Handle error
}
Purchases
# purchaseGetByTransactionId
# Look up a purchase receipt by transaction ID.
Parameters Name Default Description transactionId
string
REQUIRED Transaction ID of the purchase to look up. Returns Name Description purchase
nkruntime.ValidatedPurchaseAroundOwner A validated purchase. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let transactionId = '809346e9-3d71-4aa8-9938-0ea566a0ed11' ;
let result : nkruntime.ValidatedPurchaseOwner ;
try {
result = nk . purchaseGetByTransactionId ( transactionId );
} catch ( error ) {
// Handle error
}
purchasesList
# List stored validated purchase receipts.
Parameters Name Default Description userId
string Filter by user ID. Can be an empty string to list purchases for all users. limit
number 100 Limit number of records retrieved. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. Returns Name Description listPurchases
nkruntime.ValidatedPurchaseList A page of stored validated purchases and possibly a cursor. If cursor is empty/null there are no further results. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
let validation : nkruntime.ValidatedPurchaseList ;
try {
validation = nk . purchasesList ( userId );
} catch ( error ) {
// Handle error
}
purchaseValidateApple
# Validates and stores the purchases present in an Apple App Store Receipt.
Parameters Name Default Description userId
string
REQUIRED The user ID of the owner of the receipt. receipt
string
REQUIRED Base-64 encoded receipt data returned by the purchase operation itself. persist
bool true Persist the purchase so that seenBefore can be computed to protect against replay attacks. passwordOverride
string Override the iap.apple.shared_password provided in your configuration. Returns Name Description validation
nkruntime.ValidatePurchaseResponse The resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let userId = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
let receipt = '<base64-receipt-data>' ;
let validation : nkruntime.ValidatePurchaseResponse ;
try {
validation = nk . purchaseValidateApple ( userId , receipt );
} catch ( error ) {
// Handle error
}
purchaseValidateFacebookInstant
# Validates and stores a purchase receipt from Facebook Instant Games.
Parameters Name Default Description userId
string
REQUIRED The user ID of the owner of the receipt. signedRequest
string
REQUIRED The Facebook Instant signedRequest receipt data. persist
bool true Persist the purchase so that seenBefore can be computed to protect against replay attacks. Returns Name Description validation
nkruntime.ValidatePurchaseResponse The resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
let signedRequest = '<signedRequest-data>' ;
try {
validation = nk . purchaseValidateFacebookInstant ( userId , signedRequest );
} catch ( error ) {
// Handle error
}
purchaseValidateGoogle
# Validates and stores a purchase receipt from the Google Play Store.
Parameters Name Default Description userId
string
REQUIRED The user ID of the owner of the receipt. receipt
string
REQUIRED JSON encoded Google receipt. persist
bool true Persist the purchase so that seenBefore can be computed to protect against replay attacks. Returns Name Description validation
nkruntime.ValidatePurchaseResponse The resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let userId = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
let receipt = '{\"json\":{\"orderId \":\"..\",\"packageName \":\"..\",\"productId \":\"..\",\"purchaseTime\":1607721533824,\"purchaseState\":0,\"purchaseToken\":\"..\",\"acknowledged\":false},\"signature \":\"..\",\"skuDetails \":{\"productId\":\"..\",\"type\":\"inapp\",\"price\":\"u20ac82.67\",\"price_amount_micros\":82672732,\"price_currency_code\":\"EUR\",\"title\":\"..\",\"description\":\"..\",\"skuDetailsToken\":\"..\"}}' ;
let validation : nkruntime.ValidatePurchaseResponse ;
try {
validation = nk . purchaseValidateGoogle ( userId , receipt );
} catch ( error ) {
// Handle error
}
purchaseValidateHuawei
# Validates and stores a purchase receipt from the Huawei App Gallery.
Parameters Name Default Description userId
string
REQUIRED The user ID of the owner of the receipt. receipt
string
REQUIRED The Huawei receipt data. signature
string
REQUIRED The receipt signature. persist
bool true Persist the purchase so that seenBefore can be computed to protect against replay attacks. Returns Name Description validation
nkruntime.ValidatePurchaseResponse The resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
let userId = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
let receipt = '<receipt-data>' ;
let signature = '<signature-data>' ;
let validation : nkruntime.ValidatePurchaseResponse ;
try {
validation = nk . purchaseValidateHuawei ( userId , receipt , signature );
} catch ( error ) {
// Handle error
}
Satori
# getSatori
# Get the Satori client.
Parameters Name Default Description Returns Name Description satori
*nkruntime.Satori The satori client. error
error An optional error value if an error occurred.
1
const satori = nk . getSatori ();
satoriAuthenticate
# Create a new identity.
Parameters Name Default Description id
string
REQUIRED The identifier of the identity. properties
nkruntime.AuthPropertiesUpdate null Opt. Properties to update. ip
string An optional client IP address to pass on to Satori for geo-IP lookup. Returns Name Description error
error An optional error value if an error occurred.
1
2
const userId = "user-id" ;
satori . authenticate ( userId );
satoriExperimentsList
# List experiments.
Parameters Name Default Description id
string
REQUIRED The identifier of the identity. names
string[] Optional list of experiment names to filter. Returns Name Description experiments
*nkruntime.Experiment[] The experiment list. error
error An optional error value if an error occurred.
1
const experiments = satori . experimentsList ( "identityId" , [ "experimentName1" , "experimentName2" ]);
satoriFlagsList
# List flags.
Parameters Name Default Description id
string
REQUIRED The identifier of the identity. names
string[] Optional list of flag names to filter. Returns Name Description flags
*nkruntime.Flag[] The flag list. error
error An optional error value if an error occurred.
1
const flags = satori . flagsList ( "identityId" , [ "flagName1" , "flagName2" ]);
satoriLiveEventsList
# List live events.
Parameters Name Default Description id
string
REQUIRED The identifier of the identity. names
string[] Optional list of live event names to filter. Returns Name Description liveEvents
*nkruntime.LiveEvent[] The live event list. error
error An optional error value if an error occurred.
1
const liveEvents = satori . liveEventsList ( "identityId" , [ "liveEventName1" , "liveEventName2" ])
satoriMessageDelete
# Delete message.
Parameters Name Default Description id
string
REQUIRED The identifier of the identity. messageId
string
REQUIRED The identifier of the message. Returns Name Description error
error An optional error value if an error occurred.
1
satori . messageDelete ( "identityId" , "messageId" );
satoriMessagesList
# List messages.
Parameters Name Default Description id
string
REQUIRED The identifier of the identity. limit
int 100 The max number of messages to return. forward
bool true True if listing should be older messages to newer, false if reverse. cursor
string A pagination cursor, if any. Returns Name Description messages
*nkruntime.Message[] The message list. error
error An optional error value if an error occurred.
1
2
3
4
let limit = 20 ;
let forward = true ;
const messages = satori . messagesList ( "identityId" , limit , forward );
satoriMessageUpdate
# Update message.
Parameters Name Default Description id
string
REQUIRED The identifier of the identity. readTime
int
REQUIRED The time the message was read at the client. consumeTime
int
REQUIRED 0 The time the message was consumed by the identity. Returns Name Description error
error An optional error value if an error occurred.
1
satori . messageUpdate ( "identityId" , "<readTime>" , "<consumeTime>" );
satoriPropertiesGet
# Get identity properties.
Parameters Name Default Description id
string
REQUIRED The identifier of the identity. Returns Name Description properties
*nkruntime.Properties The identity properties. error
error An optional error value if an error occurred.
1
const properties = satori . propertiesGet ( "identityId" );
satoriPropertiesUpdate
# Update identity properties.
Parameters Name Default Description id
string
REQUIRED The identifier of the identity. properties
nkruntime.PropertiesUpdate
REQUIRED The identity properties to update. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
satori . propertiesUpdate ( "identityId" , {
default : {
"language" : "japanese"
},
custom : {
"customProperty" : "someValue"
}
});
satoriPublishEvents
# Publish an event.
Parameters Name Default Description id
string
REQUIRED The identifier of the identity. events
nkruntime.Event[]
REQUIRED An array of events to publish. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
satori . eventsPublish ( "identityId" , [
{
name : "eventName" ,
id : "optionalEventId" ,
metadata : {
"someProperty" : "someValue"
},
value : "someValue" ,
timestamp : Date.now ()
}
]);
Sessions
# sessionDisconnect
# Disconnect a session.
Parameters Name Default Description sessionId
string
REQUIRED The ID of the session to be disconnected. reason
nkruntime.PresenceReason
REQUIRED The reason for the session disconnect. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
const sessionId = "81550806-a751-45c3-a667-574c916e06aa" ;
const reason = nkruntime . PresenceReason . PresenceReasonDisconnect ;
nk . sessionDisconnect ( sessionId , reason );
sessionLogout
# Log out a user from their current session.
Parameters Name Default Description userId
string
REQUIRED The ID of the user to be logged out. token
string The current session authentication token. If the current auth and refresh tokens are not provided, all user sessions will be logged out. refreshToken
string The current session refresh token. If the current auth and refresh tokens are not provided, all user sessions will be logged out. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
const userId = "1467c4f5-df88-43df-98c5-6bd09723aa70" ;
const token = "<Token>" ;
const refreshToken = "<RefreshToken>" ;
nk . sessionLogout ( userId , token , refreshToken );
Storage
# storageDelete
# Remove one or more objects by their collection/keyname and optional user.
Parameters Name Default Description objectIds
nkruntime.StorageDeleteRequest[]
REQUIRED An array of object identifiers to be deleted. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
let userId = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let friendUserId = '8d98ee3f-8c9f-42c5-b6c9-c8f79ad1b820' ;
let objectIds : nkruntime.StorageDeleteRequest [] = [
{ collection : 'save' , key : 'save1' , userId },
{ collection : 'save' , key : 'save2' , userId },
{ collection : 'public' , key : 'progress' , userId : friendUserId },
];
try {
nk . storageDelete ( objectIds );
} catch ( error ) {
// Handle error
}
storageIndexList
# List storage index entries
Parameters Name Default Description indexName
string
REQUIRED Name of the index to list entries from. queryString
string
REQUIRED Query to filter index entries. limit
int
REQUIRED Maximum number of results to be returned. order
[]string The storage object fields to sort the query results by. The prefix '-' before a field name indicates descending order. All specified fields must be indexed and sortable. callerId
string User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permission checks are bypassed. Returns Name Description objects
nkruntime.StorageIndexResult A list of storage objects. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
const name = "index_name" ;
const query = "+field1:1 field2:foo" ;
const limit = 10 ;
try {
let objects = nk . storageIndexList ( name , query , limit );
} ( catch err ) {
// Handle error
}
storageList
# List records in a collection and page through results. The records returned can be filtered to those owned by the user or "" for public records.
Parameters Name Default Description userId
string
REQUIRED User ID to list records for or "" (empty string) for public records. collection
string
REQUIRED Collection to list data from. limit
number 100 Limit number of records retrieved. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. Returns Name Description objects
nkruntime.StorageObjectList A list of storage objects. cursor
string Pagination cursor. Will be set to "" or null when fetching last available page. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let user_id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let result : nkruntime.StorageObjectList = {};
try {
let result = nk . storageList ( user_id , 'collection' , 10 );
} catch ( error ) {
// Handle error
}
storageRead
# Fetch one or more records by their bucket/collection/keyname and optional user.
Parameters Name Default Description objectIds
nkruntime.StorageReadRequest[]
REQUIRED An array of object identifiers to be fetched. Returns Name Description objects
nkruntime.StorageObject[] A list of storage records matching the parameters criteria. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let userId = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let objectIds : nkruntime.StorageReadRequest [] = [
{ collection : 'save' , key : 'save1' , userId : userId },
{ collection : 'save' , key : 'save2' , userId },
{ collection : 'save' , key : 'save3' , userId },
];
let results : nkruntime.StorageObject [] = [];
try {
results = nk . storageRead ( objectIds );
} catch ( error ) {
// Handle error
}
storageWrite
# Write one or more objects by their collection/keyname and optional user.
Parameters Name Default Description objectIds
nkruntime.StorageWriteRequest[]
REQUIRED An array of object identifiers to be written. Returns Name Description acks
nkruntime.StorageWriteAck[] A list of acks with the version of the written objects. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let userId = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let newObjects : nkruntime.StorageWriteRequest [] = [
{ collection : 'save' , key : 'save1' , userId , value : {} },
{ collection : 'save' , key : 'save2' , userId , value : {} },
{ collection : 'save' , key : 'save3' , userId , value : {}, permissionRead : 2 , permissionWrite : 1 },
{ collection : 'save' , key : 'save3' , userId , value : {}, version : '<some_version>' , permissionRead : 1 , permissionWrite : 1 }
];
try {
nk . storageWrite ( newObjects );
} catch ( error ) {
// Handle error
}
// Storage Index List
const name = "index_name" ;
Streams
# streamClose
# Close a stream and remove all presences on it.
Parameters Name Default Description stream
nkruntime.Stream
REQUIRED A stream object. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
try {
let stream : nkruntime.Stream ; // An existing stream object
nk . streamClose ( stream );
} catch ( err ) {
// Handle error
}
streamCount
# Get a count of stream presences.
Parameters Name Default Description stream
nkruntime.Stream
REQUIRED A stream object. Returns Name Description countByStream
number Number of current stream presences. error
error An optional error value if an error occurred.
1
2
3
4
5
6
try {
let stream : nkruntime.Stream ; // An existing stream object
const count = nk . streamCount ( stream );
} catch ( err ) {
// Handle error
}
streamSend
# Send data to presences on a stream.
Parameters Name Default Description stream
nkruntime.Stream
REQUIRED A stream object. data
string
REQUIRED The data to send. presences
nkruntime.Presence[] all Array of presences to receive the sent data. reliable
bool true Whether the sender has been validated prior. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
try {
let stream : nkruntime.Stream ; // An existing stream object
let presences : nkruntime.Presence []; // An existing presences array
const data = "<Data>" ;
const reliable = true ;
nk . streamSend ( stream , data , presences , reliable );
} catch ( err ) {
// Handle error
}
streamSendRaw
# Send a message to presences on a stream.
Parameters Name Default Description stream
nkruntime.Stream
REQUIRED A stream object. msg
REQUIRED The message to send. presences
nkruntime.Presence[] all Array of presences to receive the sent data. reliable
bool true Whether the sender has been validated prior. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
try {
let stream : nkruntime.Stream ; // An existing stream object
let presences : nkruntime.Presence []; // An existing presences array
const envelope = {}; // A data object
const reliable = true ;
nk . streamSendRaw ( stream , envelope , presences , reliable );
} catch ( err ) {
// Handle error
}
streamUserGet
# Retrieve a stream presence and metadata by user ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to fetch information for. sessionId
string
REQUIRED The current session ID for the user. stream
nkruntime.Stream
REQUIRED A stream object. Returns Name Description meta
nkruntime.Presence Presence for the user. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
try {
let stream : nkruntime.Stream ; // An existing stream object
const userId = "7d8252ef-8bc7-4d7d-a828-e99733046355" ;
const sessionId = "ef54eece-ddd1-4c62-b567-6d6c8c902c9c" ;
const presence = nk . streamUserGet ( userId , sessionId , stream );
} catch ( err ) {
// Handle error
}
streamUserJoin
# Add a user to a stream.
Parameters Name Default Description userId
string
REQUIRED The user ID to be added. sessionId
string
REQUIRED The current session ID for the user. stream
nkruntime.Stream
REQUIRED A stream object. hidden
bool
REQUIRED Whether the user will be marked as hidden. persistence
bool
REQUIRED Whether message data should be stored in the database. status
string
REQUIRED User status message. Returns Name Description success
bool Whether the user was successfully added. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
try {
let stream : nkruntime.Stream ; // An existing stream object
const userId = "7d8252ef-8bc7-4d7d-a828-e99733046355" ;
const sessionId = "ef54eece-ddd1-4c62-b567-6d6c8c902c9c" ;
const hidden = false ;
const persistence = true ;
const status = "Some Status" ;
nk . streamUserJoin ( userId , sessionId , stream , hidden , persistence , status );
} catch ( err ) {
// Handle error
}
streamUserKick
# Kick a user from a stream.
Parameters Name Default Description presence
nkruntime.Presence
REQUIRED The presence to be kicked. stream
nkruntime.Stream
REQUIRED A stream object. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
try {
let stream : nkruntime.Stream ; // An existing stream object
let presence : nkruntime.Presence ; // An existing presence object
nk . streamUserKick ( presence , stream );
} catch ( err ) {
// Handle error
}
streamUserLeave
# Remove a user from a stream.
Parameters Name Default Description userId
string
REQUIRED The user ID to be removed. sessionId
string
REQUIRED The current session ID for the user. stream
nkruntime.Stream
REQUIRED A stream object. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
try {
let stream : nkruntime.Stream ; // An existing stream object
const userId = "7d8252ef-8bc7-4d7d-a828-e99733046355" ;
const sessionId = "ef54eece-ddd1-4c62-b567-6d6c8c902c9c" ;
nk . streamUserLeave ( userId , sessionId , stream );
} catch ( err ) {
// Handle error
}
streamUserList
# List all users currently online and connected to a stream.
Parameters Name Default Description stream
nkruntime.Stream
REQUIRED A stream object. includeHidden
bool Include stream presences marked as hidden in the results. includeNotHidden
bool Include stream presences not marked as hidden in the results. Returns Name Description presences
nkruntime.Presences[] Array of stream presences and their information. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
try {
let stream : nkruntime.Stream ; // An existing stream object
const includeHidden = true ;
const includeNotHidden = true ;
const presences = nk . streamUserList ( stream , includeHidden , includeNotHidden );
} catch ( err ) {
// Handle error
}
streamUserUpdate
# Update a stream user by ID.
Parameters Name Default Description userId
string
REQUIRED The user ID to be updated. sessionId
string
REQUIRED The current session ID for the user. stream
nkruntime.Stream
REQUIRED A stream object. hidden
bool
REQUIRED Whether the user will be marked as hidden. persistence
bool
REQUIRED Whether message data should be stored in the database. status
string
REQUIRED User status message. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
try {
let stream : nkruntime.Stream ; // An existing stream object
const userId = "7d8252ef-8bc7-4d7d-a828-e99733046355" ;
const sessionId = "ef54eece-ddd1-4c62-b567-6d6c8c902c9c" ;
const hidden = true ;
const persistence = true ;
nk . streamUserUpdate ( userId , sessionId , stream , hidden , persistence );
} catch ( err ) {
// Handle error
}
Subscriptions
# subscriptionGetByProductId
# Look up a subscription by product ID.
Parameters Name Default Description userId
string
REQUIRED The user ID of the subscription owner. subscriptionId
string
REQUIRED Transaction ID of the purchase to look up. Returns Name Description subscription
nkruntime.ValidatedSubscription A validated subscription. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let userId = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
let subscriptionId = 'subscriptionId' ;
let result : nkruntime.ValidatedSubscription ;
try {
result = nk . subscriptionGetByProductId ( userId , subscriptionId );
} catch ( error ) {
// Handle error
}
subscriptionsList
# List stored validated subscriptions.
Parameters Name Default Description userId
string Filter by user ID. Can be an empty string to list subscriptions for all users. limit
number 100 Limit number of records retrieved. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. Returns Name Description listSubscriptions
nkruntime.SubscriptionList A page of stored validated subscriptions and possibly a cursor. If cursor is empty/null there are no further results. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
let validation : nkruntime.ValidatedPurchaseList ;
try {
validation = nk . subscriptionsList ( userId );
} catch ( error ) {
// Handle error
}
subscriptionValidateApple
# Validates and stores the subscription present in an Apple App Store Receipt.
Parameters Name Default Description userId
string
REQUIRED The user ID of the owner of the receipt. receipt
string
REQUIRED Base-64 encoded receipt data returned by the purchase operation itself. persist
bool true Persist the purchase so that seenBefore can be computed to protect against replay attacks. passwordOverride
string Override the iap.apple.shared_password provided in your configuration. Returns Name Description validation
nkruntime.ValidateSubscriptionResponse The resulting successfully validated subscription. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let userId = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
let receipt = '<base64-receipt-data>' ;
let validation : nkruntime.ValidateSubscriptionResponse ;
try {
validation = nk . subscriptionValidateApple ( userId , receipt );
} catch ( error ) {
// Handle error
}
subscriptionValidateGoogle
# Validates and stores a subscription purchase receipt from the Google Play Store.
Parameters Name Default Description userId
string
REQUIRED The user ID of the owner of the receipt. receipt
string
REQUIRED JSON encoded Google receipt. persist
bool true Persist the subscription. Returns Name Description validation
nkruntime.ValidateSubscriptionResponse The resulting successfully validated subscriptions. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let userId = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
let receipt = '{\"json\":{\"orderId \":\"..\",\"packageName \":\"..\",\"productId \":\"..\",\"purchaseTime\":1607721533824,\"purchaseState\":0,\"purchaseToken\":\"..\",\"acknowledged\":false},\"signature \":\"..\",\"skuDetails \":{\"productId\":\"..\",\"type\":\"inapp\",\"price\":\"u20ac82.67\",\"price_amount_micros\":82672732,\"price_currency_code\":\"EUR\",\"title\":\"..\",\"description\":\"..\",\"skuDetailsToken\":\"..\"}}' ;
let validation : nkruntime.ValidatePurchaseResponse ;
try {
validation = nk . subscriptionValidateGoogle ( userId , receipt );
} catch ( error ) {
// Handle error
}
Tournaments
# tournamentAddAttempt
# Add additional score attempts to the owner's tournament record. This overrides the max number of score attempts allowed in the tournament for this specific owner.
Parameters Name Default Description id
string
REQUIRED The unique identifier for the tournament to update. owner
string
REQUIRED The owner of the records to increment the count for. count
number
REQUIRED The number of attempt counts to increment. Can be negative to decrease count. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let owner = 'leaderboard-record-owner' ;
let count = - 10 ;
try {
nk . tournamentAddAttempt ( id , owner , count );
} catch ( error ) {
// Handle error
}
tournamentCreate
# Setup a new dynamic tournament with the specified ID and various configuration settings. The underlying leaderboard will be created if it doesn't already exist, otherwise its configuration will not be updated.
Parameters Name Default Description id
string
REQUIRED The unique identifier for the new tournament. This is used by clients to submit scores. authoritative
bool true Whether the tournament created is server authoritative. sortOrder
string The sort order for records in the tournament. Possible values are "asc" or "desc". operator
string The operator that determines how scores behave when submitted. The possible values are "best", "set", or "incr". resetSchedule
string The cron format used to define the reset schedule for the tournament. This controls when the underlying leaderboard resets and the tournament is considered active again. metadata
object The metadata you want associated to the tournament. Some good examples are weather conditions for a racing game. title
string The title of the tournament. description
string The description of the tournament. category
number A category associated with the tournament. This can be used to filter different types of tournaments. Between 0 and 127. startTime
number The start time of the tournament. Leave empty for immediately or a future time. endTime
number never The end time of the tournament. When the end time is elapsed, the tournament will not reset and will cease to exist. Must be greater than startTime if set. duration
number
REQUIRED The active duration for a tournament. This is the duration when clients are able to submit new records. The duration starts from either the reset period or tournament start time whichever is sooner. A game client can query the tournament for results between end of duration and next reset period. maxSize
number Maximum size of participants in a tournament. maxNumScore
number 1000000 Maximum submission attempts for a tournament record. joinRequired
bool false Whether the tournament needs to be joined before a record write is allowed. enableRanks
bool false Whether to enable rank values for the tournament. Returns Name Description error
error An optional error value if an error occurred.
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
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let authoritative = false
let sortOrder = nkruntime . SortOrder . DESCENDING ;
let operator = nkruntime . Operator . BEST ;
let duration = 3600 ; // In seconds.
let resetSchedule = '0 12 * * *' ; // Noon UTC each day.
let metadata = {
weatherConditions : 'rain' ,
};
let title = 'Daily Dash' ;
let description = "Dash past your opponents for high scores and big rewards!" ;
let category = 1 ;
let startTime = 0 ; // Start now.
let endTime = 0 ; // Never end, repeat the tournament each day forever.
let maxSize = 10000 ; // First 10,000 players who join.
let maxNumScore = 3 ; // Each player can have 3 attempts to score.
let joinRequired = true ; // Must join to compete.
let enableRanks = true ; // Set to true to enable rank computation on leaderboard records.
try {
nk . tournamentCreate ( id , authoritative , sortOrder , operator , duration , resetSchedule , metadata , title , description , category , startTime , endTime , maxSize , maxNumScore , joinRequired , enableRanks );
} catch ( error ) {
// Handle error
}
tournamentDelete
# Delete a tournament and all records that belong to it.
Parameters Name Default Description id
string
REQUIRED The unique identifier for the tournament to delete. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
try {
nk . tournamentDelete ( id );
} catch ( error ) {
// Handle error
}
tournamentJoin
# A tournament may need to be joined before the owner can submit scores. This operation is idempotent and will always succeed for the owner even if they have already joined the tournament.
Parameters Name Default Description id
string
REQUIRED The unique identifier for the tournament to join. ownerId
string
REQUIRED The owner of the record. username
string
REQUIRED The username of the record owner. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let owner = 'leaderboard-record-owner' ;
let username = 'myusername' ;
try {
nk . tournamentJoin ( id , owner , username );
} catch ( error ) {
// Handle error
}
tournamentList
# Find tournaments which have been created on the server. Tournaments can be filtered with categories and via start and end times.
Parameters Name Default Description categoryStart
number
REQUIRED Filter tournament with categories greater or equal than this value. categoryEnd
number
REQUIRED Filter tournament with categories equal or less than this value. startTime
number Filter tournament with that start after this time. endTime
number Filter tournament with that end before this time. limit
number 10 Return only the required number of tournament denoted by this limit value. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. Returns Name Description tournamentList
nkruntime.TournamentList[] A list of tournament results and possibly a cursor. If cursor is empty/null there are no further results. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
let categoryStart = 1 ;
let categoryEnd = 2 ;
let startTime = 1538147711 ;
let endTime = 0 // All tournaments from the start time.
let limit = 100 // Number to list per page.
let results : nkruntime.TournamentList = {};
try {
results = nk . tournamentList ( categoryStart , categoryEnd , startTime , endTime , limit );
} catch ( error ) {
// Handle error
}
tournamentRanksDisable
# Disable a tournament rank cache freeing its allocated resources. If already disabled is a NOOP.
Parameters Name Default Description id
string
REQUIRED The tournament id. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
try {
nk . tournamentRanksDisable ( id );
} catch ( error ) {
// Handle error
}
tournamentRecordDelete
# Remove an owner's record from a tournament, if one exists.
Parameters Name Default Description id
string
REQUIRED The unique identifier for the tournament to delete from. owner
string
REQUIRED The owner of the score to delete. Mandatory field. Returns Name Description error
error An optional error value if an error occurred.
tournamentRecordsHaystack
# Fetch the list of tournament records around the owner.
Parameters Name Default Description id
string
REQUIRED The ID of the tournament to list records for. ownerId
string
REQUIRED The owner ID around which to show records. limit
number 10 Return only the required number of tournament records denoted by this limit value. Between 1-100. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. expiry
number 0 Time since epoch in seconds. Must be greater than 0. Returns Name Description tournamentRecordsHaystack
nkruntime.LeaderboardRecord A list of tournament records and possibly a cursor. If cursor is empty/null there are no further results. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let owner = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
let results : nkruntime.Tournament [] = [];
try {
results = nk . tournamentRecordsHaystack ( id , owner );
} catch ( error ) {
// Handle error
}
tournamentRecordsList
# List records on the specified tournament, optionally filtering to only a subset of records by their owners. Records will be listed in the preconfigured tournament sort order.
Parameters Name Default Description tournamentId
string
REQUIRED The ID of the tournament to list records for. ownerIds
string[] Array of owner IDs to filter results by. Optional. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. overrideExpiry
number 0 Optionally retrieve records from previous resets by specifying the reset point in time in UTC seconds. Must be equal or greater than 0. Returns Name Description records
nkruntime.LeaderboardRecord A page of tournament records. ownerRecords
nkruntime.LeaderboardRecord A list of owner tournament records (empty if the owners input parameter is not set). prevCursor
string An optional previous page cursor that can be used to retrieve the previous page of records (if any). nextCursor
string An optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or null when fetching last available page. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
let tournamentId = '809346e9-3d71-4aa8-9938-0ea566a0ed11' ;
let tournamentOwners = [ '385ad06e-95a5-4a1e-811a-d7ef242a3ea2' , 'f8f55fd8-2ca8-46d1-9f39-82f72fe4e2c4' ];
let limit = 10 ;
let cursor = null ;
let overrideExpiry = null ;
let result : nkruntime.TournamentRecordList ;
try {
result = nk . tournamentRecordsList ( tournamentId , tournamentOwners , limit , cursor , overrideExpiry );
} catch ( error ) {
// Handle error
}
tournamentRecordWrite
# Submit a score and optional subscore to a tournament leaderboard. If the tournament has been configured with join required this will fail unless the owner has already joined the tournament.
Parameters Name Default Description id
string
REQUIRED The unique identifier for the tournament leaderboard to submit to. owner
string
REQUIRED The owner of this score submission. Mandatory field. username
string The owner username of this score submission, if it's a user. score
number 0 The score to submit. subscore
number 0 A secondary subscore parameter for the submission. metadata
object
REQUIRED The metadata you want associated to this submission. Some good examples are weather conditions for a racing game. Returns Name Description result
nkruntime.LeaderboardRecord The newly created leaderboard record. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let id = '4ec4f126-3f9d-11e7-84ef-b7c182b36521' ;
let owner = '4c2ae592-b2a7-445e-98ec-697694478b1c' ;
let username = '02ebb2c8' ;
let score = 10 ;
let subscore = 0 ;
let metadata = {
'weather_conditions' = 'rain' ,
};
try {
nk . tournamentRecordWrite ( categoryStart , categoryEnd , startTime , endTime , limit );
} catch ( error ) {
// Handle error
}
tournamentsGetId
# Fetch one or more tournaments by ID.
Parameters Name Default Description ids
string[]
REQUIRED The table array of tournament ids. Returns Name Description result
nkruntime.Tournament[] Array of tournament records. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
let tournamentIds = [
'3ea5608a-43c3-11e7-90f9-7b9397165f34' ,
'447524be-43c3-11e7-af09-3f7172f05936' ,
]
let owner = 'leaderboard-record-owner' ;
let username = 'myusername' ;
let tournaments : nkruntime.Tournament [];
try {
tournaments = nk . tournamentsGetId ( id , owner , username );
} catch ( error ) {
// Handle error
} ``
Users
# multiUpdate
# Update account, storage, and wallet information simultaneously.
Parameters Name Default Description accountUpdates
nkruntime.AccountUpdate[]
REQUIRED Array of account information to be updated. storageWrites
nkruntime.StorageWriteRequest[]
REQUIRED Array of storage objects to be updated. storageDeletes
nkruntime.StorageDeleteRequest[]
REQUIRED Array of storage objects to be deleted. walletUpdates
nkruntime.WalletUpdate[]
REQUIRED Array of wallet updates to be made. updateLedger
bool false Whether to record this wallet update in the ledger. Returns Name Description storageWriteAcks
nkruntime.StorageWriteAck[] A list of acks with the version of the written objects. walletUpdateAcks
nkruntime.WalletUpdateResult[] A list of wallet updates results. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
let accountUpdates : nkruntime.UserUpdateAccount [];
let storageWrites : nkruntime.StorageWriteRequest [];
let walletUpdates : nkruntime.WalletUpdate [];
let updateLedger = true ;
try {
const result = nk . multiUpdate ( accountUpdates , storageWrites , walletUpdates , updateLedger );
logger . info ( "Storage Acks: " + result . storageWriteAcks . length );
logger . info ( "Wallet Acks: " + result . walletUpdateAcks . length );
} catch ( error ) {
// handle error
}
usersBanId
# Ban one or more users by ID.
Parameters Name Default Description userIds
string[]
REQUIRED An array of user IDs to ban. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
let userIds = [
'3ea5608a-43c3-11e7-90f9-7b9397165f34' ,
'447524be-43c3-11e7-af09-3f7172f05936' ,
];
try {
nk . usersBanId ( userIds );
} catch ( error ) {
// Handle error
}
usersGetId
# Fetch one or more users by ID.
Parameters Name Default Description userIds
[]string
REQUIRED An array of user IDs to fetch. Returns Name Description users
nkruntime.User[] A list of user record objects. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
let userIds = [
'3ea5608a-43c3-11e7-90f9-7b9397165f34' ,
'447524be-43c3-11e7-af09-3f7172f05936' ,
];
let users : nkruntime.Users [];
try {
users = nk . usersGetId ( userIds );
} catch ( error ) {
// Handle error
}
usersGetRandom
# Fetch one or more users randomly.
Parameters Name Default Description count
number
REQUIRED The number of users to fetch. Returns Name Description users
nkruntime.User[] A list of user record objects. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let users : nkruntime.Users [];
try {
users = nk . usersGetRandom ( 100 );
} catch ( error ) {
// Handle error
}
usersGetUsername
# Fetch one or more users by username.
Parameters Name Default Description usernames
[]string
REQUIRED An array of usernames to fetch. Returns Name Description users
nkruntime.User[] A list of user record objects. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
let usernames = [
'b7865e7e' ,
'c048ba7a' ,
];
let users : nkruntime.Users [];
try {
users = nk . usersGetUsername ( usernames );
} catch ( error ) {
// Handle error
}
usersUnbanId
# Unban one or more users by ID.
Parameters Name Default Description userIds
string[]
REQUIRED An array of user IDs to unban. Returns Name Description error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
let userIds = [
'3ea5608a-43c3-11e7-90f9-7b9397165f34' ,
'447524be-43c3-11e7-af09-3f7172f05936' ,
];
try {
nk . usersUnbanId ( userIds );
} catch ( error ) {
// Handle error
}
Utils
# aes128Decrypt
# Decrypt an aes128 encrypted string.
Parameters Name Default Description input
string
REQUIRED The string to be decrypted. key
string
REQUIRED The 16 Byte decryption key. Returns Name Description clearText
string The deciphered input. error
error An optional error value if an error occurred.
1
2
3
4
5
try {
let clearText = nk . aes128Decrypt ( '48656C6C6F20776F726C64' , 'goldenbridge_key' );
} catch ( error ) {
// Handle error
}
aes128Encrypt
# aes128 encrypt a string input.
Parameters Name Default Description input
string
REQUIRED The string which will be aes128 encrypted. key
string
REQUIRED The 16 Byte encryption key. Returns Name Description cipherText
string The ciphered input. error
error An optional error value if an error occurred.
1
2
3
4
5
try {
let cipherText = nk . aes128Encrypt ( 'Hello world' , 'goldenbridge_key' );
} catch ( error ) {
// Handle error
}
aes256Decrypt
# Decrypt an aes256 encrypted string.
Parameters Name Default Description input
string
REQUIRED The string to be decrypted. key
string
REQUIRED The 32 Byte decryption key. Returns Name Description clearText
string The deciphered input. error
error An optional error value if an error occurred.
1
2
3
4
5
try {
let clearText = nk . aes256Decrypt ( '48656C6C6F20776F726C64' , 'goldenbridge_key' );
} catch ( error ) {
// Handle error
}
aes256Encrypt
# aes256 encrypt a string input.
Parameters Name Default Description input
string
REQUIRED The string which will be aes256 encrypted. key
string
REQUIRED The 32 Byte encryption key. Returns Name Description cipherText
string The ciphered input. error
error An optional error value if an error occurred.
1
2
3
4
5
try {
let cipherText = nk . aes256Encrypt ( 'Hello world' , 'goldenbridge_key' );
} catch ( error ) {
// Handle error
}
aesDecrypt
# aes decrypt a base 64 encoded string input.
Parameters Name Default Description keySize
int
REQUIRED The size in bytes of the decryption key. input
string
REQUIRED The string which will be decrypted. key
string
REQUIRED The encryption key. Returns Name Description clearText
string The deciphered and decoded input. error
error An optional error value if an error occurred.
1
2
3
4
5
try {
let clearText = nk . aesDecrypt ( 16 , '48656C6C6F20776F726C64' , 'goldenbridge_key' );
} catch ( error ) {
// Handle error
}
aesEncrypt
# aes encrypt a string input and return the cipher text base64 encoded.
Parameters Name Default Description keySize
int
REQUIRED The size in bytes of the encryption key. input
string
REQUIRED The string which will be encrypted. key
string
REQUIRED The encryption key. Returns Name Description cipherText
string The ciphered and base64 encoded input. error
error An optional error value if an error occurred.
1
2
3
4
5
try {
let cipherText = nk . aesEncrypt ( 16 , 'Hello world' , 'goldenbridge_key' );
} catch ( error ) {
// Handle error
}
base16Decode
# Decode a base16 encoded string.
Parameters Name Default Description input
string
REQUIRED The string to be decoded. Returns Name Description out
ArrayBuffer Decoded data. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result : string ;
try {
result = nk . base16Decode ( '48656C6C6F20776F726C64' );
} catch ( error ) {
// Handle error
}
base16Encode
# base16 encode a string or ArrayBuffer input.
Parameters Name Default Description input
string
REQUIRED The string to be encoded. Returns Name Description out
string Encoded string. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result : string ;
try {
result = nk . base16Encode ( 'Hello World' );
} catch ( error ) {
// Handle error
}
base64Decode
# Decode a base64 encoded string.
Parameters Name Default Description input
string
REQUIRED The string which will be base64 decoded. padding
bool true Pad the string if padding is missing. Returns Name Description out
ArrayBuffer Decoded data. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result : string ;
try {
result = nk . base64Decode ( 'SGVsbG8gd29ybGQ=' );
} catch ( error ) {
// Handle error
}
base64Encode
# Base64 encode a string or ArrayBuffer input.
Parameters Name Default Description input
string
REQUIRED The string which will be base64 encoded. Returns Name Description out
string Encoded string. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result : string ;
try {
result = nk . base64Encode ( 'Hello World' );
} catch ( error ) {
// Handle error
}
base64UrlDecode
# Decode a base64 URL encoded string.
Parameters Name Default Description input
string
REQUIRED The string to be decoded. Returns Name Description out
ArrayBuffer Decoded data. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result : string ;
try {
result = nk . base64UrlDecode ( 'SGVsbG8gd29ybGQ=' );
} catch ( error ) {
// Handle error
}
base64UrlEncode
# Base64 URL encode a string or ArrayBuffer input.
Parameters Name Default Description input
string
REQUIRED The string which will be base64 URL encoded. Returns Name Description out
string Encoded string. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result : string ;
try {
result = nk . base64UrlEncode ( 'Hello World' );
} catch ( error ) {
// Handle error
}
bcryptCompare
# Compare hashed input against a plaintext input.
Parameters Name Default Description input
string
REQUIRED The bcrypted input string. plaintext
string
REQUIRED Plaintext input to compare against. Returns Name Description result
bool True if they are the same, false otherwise. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result : boolean ;
try {
result = nk . bcryptCompare ( '$2a$04$bl3tac7Gwbjy04Q8H2QWLuUOEkpoNiAeTxazxi4fVQQRMGbMaUHQ2' , '123456' );
} catch ( error ) {
// Handle error
}
bcryptHash
# Generate one-way hashed string using bcrypt.
Parameters Name Default Description input
string
REQUIRED The input string to bcrypt. Returns Name Description hash
string Hashed string. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result : string ;
try {
result = nk . bcryptHash ( 'Hello World' );
} catch ( error ) {
// Handle error
}
binaryToString
# Convert binary data to string.
Parameters Name Default Description data
ArrayBuffer
REQUIRED The binary data to be converted. Returns Name Description result
string The resulting string. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result : string ;
try {
result = nk . binaryToString ( '\x48\x65\x72\x6F\x69\x63\x4C\x61\x62\x73' );
} catch ( error ) {
// Handle error
}
cronNext
# Parses a CRON expression and a timestamp in UTC seconds, and returns the next matching timestamp in UTC seconds.
Parameters Name Default Description expression
string
REQUIRED A valid CRON expression in standard format, for example "0 0 * * *" (meaning at midnight). timestamp
number
REQUIRED A time value expressed as UTC seconds. Returns Name Description next_ts
number The next UTC seconds timestamp (number) that matches the given CRON expression, and is immediately after the given timestamp. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let result : number ;
try {
let expr = '0 0 * * 1' ;
let ts = Math . floor ( Date . now () / 1000 );
result = nk . cronNext ( expr , ts );
} catch ( error ) {
// Handle error
}
cronPrev
# Parses a CRON expression and a timestamp in UTC seconds, and returns the previous matching timestamp in UTC seconds.
Parameters Name Default Description expression
string
REQUIRED A valid CRON expression in standard format, for example "0 0 * * *" (meaning at midnight). timestamp
number
REQUIRED A time value expressed as UTC seconds. Returns Name Description prev_ts
number The previous UTC seconds timestamp (number) that matches the given CRON expression, and is immediately before the given timestamp. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let result : number ;
try {
let expr = '0 0 * * 1' ;
let ts = Math . floor ( Date . now () / 1000 );
result = nk . cronPrev ( expr , ts );
} catch ( error ) {
// Handle error
}
fileRead
# Read file from user device.
Parameters Name Default Description relPath
string
REQUIRED Relative path to the file to be read. Returns Name Description fileRead
string The read file contents. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let result : string ;
let relativePath = '<RelativePath>' ;
try {
result = nk . fileRead ( relativePath );
} catch ( error ) {
// Handle error
}
hmacSHA256Hash
# Create a HMAC-SHA256 hash from input and key.
Parameters Name Default Description input
string
REQUIRED The input string to hash. key
string
REQUIRED The hashing key. Returns Name Description mac
string Hashed input as a string using the key. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let hash : string ;
try {
hash = nk . hmacSha256Hash ( 'some input text to hash' , 'some_key' );
} catch ( error ) {
// Handle error
}
httpRequest
# Send an HTTP request that returns a data type containing the result of the HTTP response.
Parameters Name Default Description url
string
REQUIRED The URL of the web resource to request. method
string
REQUIRED The HTTP method verb used with the request. headers
string
REQUIRED A table of headers used with the request. content
string
REQUIRED The bytes to send with the request. timeout
number 5000 Timeout of the request in milliseconds. insecure
bool false Set to true to skip request TLS validations. Returns Name Description returnVal
nkruntime.httpResponse Code, Headers, and Body response values for the HTTP response. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let method : nkruntime.RequestMethod = 'get' ;
let headers = {
'Content-Type' : 'application/json' ,
'Accept' : 'application/json' ,
};
let body = JSON . stringify ({});
let res = {} as nkruntime . HttpResponse ;
try {
res = nk . httpRequest ( 'https://google.com' , method , headers , body );
} catch ( error ) {
// Handle error
}
jwtGenerate
# Generate a JSON Web Token.
Parameters Name Default Description signingMethod
string
REQUIRED The signing method to be used, either HS256 or RS256. claims
[]string
REQUIRED The JWT payload. Returns Name Description signedToken
string The newly generated JWT. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let result : string
let signingKey = 'goldenbridge_key' ;
let claims = { email : 'test@heroiclabs.com' }
try {
result = nk . jwtGenerate ( 'HS256' , signingKey , claims );
} catch ( error ) {
// Handle error
}
md5Hash
# Create an md5 hash from the input.
Parameters Name Default Description input
string
REQUIRED The input string to hash. Returns Name Description hash
string A string with the md5 hash of the input. error
error An optional error value if an error occurred.
1
2
let input = 'somestring' ;
let hashed = nk . md5Hash ( input );
rsaSHA256Hash
# Create a RSA encrypted SHA256 hash from the input.
Parameters Name Default Description input
string
REQUIRED The input string to hash. key
string
REQUIRED The RSA private key. Returns Name Description signature
string A string with the RSA encrypted SHA256 hash of the input. error
error An optional error value if an error occurred.
1
const cipherText = nk . rsaSha256Hash ( "Hello world" , "<RSAPrivateKey>" )
sha256Hash
# Create an SHA256 hash from the input.
Parameters Name Default Description input
string
REQUIRED The input string to hash. Returns Name Description hash
string A string with the SHA256 hash of the input. error
error An optional error value if an error occurred.
1
const cipherText = nk . sha256Hash ( "Hello world" );
sqlExec
# Execute an arbitrary SQL query and return the number of rows affected. Typically, an "INSERT", "DELETE", or "UPDATE" statement with no return columns.
Parameters Name Default Description query
string
REQUIRED A SQL query to execute. parameters
any[]
REQUIRED Arbitrary parameters to pass to placeholders in the query. Returns Name Description rowsAffected
number A list of matches matching the parameters criteria. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let query = 'DELETE FROM leaderboard_record WHERE expires_at > 0 AND expires_at <= $1' ;
let parameters = [ Math . floor ( Date . now () / 1000 ) ];
let result : nkruntime.SqlExecResult ;
try {
result = nk . sqlExec ( query , parameters );
} catch ( error ) {
// Handle error
}
sqlQuery
# Execute an arbitrary SQL query that is expected to return row data. Typically a "SELECT" statement.
Parameters Name Default Description query
string
REQUIRED A SQL query to execute. parameters
any[]
REQUIRED Arbitrary parameters to pass to placeholders in the query. Returns Name Description result
nkruntime.SqlQueryResult An array of rows and the respective columns and values. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
let query = 'SELECT username, create_time FROM users ORDER BY create_time DESC LIMIT 100' ;
let parameters : any [] = [];
let rows : nkruntime.SqlQueryResult = [];
try {
rows = nk . sqlQuery ( query , parameters );
} catch ( error ) {
// Handler error
}
stringToBinary
# Convert string data to binary.
Parameters Name Default Description str
string
REQUIRED The string to be converted. Returns Name Description result
ArrayBuffer The resulting binary data. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
let result : Uint8Array
try {
result = nk . stringToBinary ( 'HeroicLabs' );
} catch ( error ) {
// Handle error
}
uuidV4
# Generate a version 4 UUID in the standard 36-character string representation.
Parameters Name Default Description Returns Name Description uuid
string The newly generated version 4 UUID identifier string. error
error An optional error value if an error occurred.
1
let uuid = nk . uuidV4 ();
Wallets
# walletLedgerList
# List all wallet updates for a particular user from oldest to newest.
Parameters Name Default Description userId
string
REQUIRED The ID of the user to list wallet updates for. limit
number 100 Limit number of results. cursor
string Pagination cursor from previous result. Don't set to start fetching from the beginning. Returns Name Description runtimeItems
nkruntime.WalletLedgerItem[] A JavaScript Object containing wallet entries with Id, UserId, CreateTime, UpdateTime, Changeset, Metadata parameters, and possibly a cursor. If cursor is empty/null there are no further results. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
let userId = '8f4d52c7-bf28-4fcf-8af2-1d4fcf685592' ;
let results : nkruntime.WalletLedgerList [];
try {
results = nk . walletLedgerList ( userId );
} catch ( error ) {
// Handle error
}
walletLedgerUpdate
# Update the metadata for a particular wallet update in a user's wallet ledger history. Useful when adding a note to a transaction for example.
Parameters Name Default Description itemId
string
REQUIRED The ID of the wallet ledger item to update. metadata
object
REQUIRED The new metadata to set on the wallet ledger item. Returns Name Description updateWalletLedger
nkruntime.WalletLedgerItem The updated wallet ledger item. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
let id = '2745ba53-4b43-4f83-ab8f-93e9b677f33a' ;
let metadata = {
gameResult : 'loss'
};
let result : nkruntime.WalletLedgerResult ;
try {
result = nk . walletLedgerUpdate ( id , metadata );
} catch ( error ) {
// Handle error
}
walletsUpdate
# Update one or more user wallets with individual changesets. This function will also insert a new wallet ledger item into each user's wallet history that tracks their update.
Parameters Name Default Description updates
nkruntime.WalletUpdate[]
REQUIRED The set of user wallet update operations to apply. updateLedger
bool false Whether to record this update in the ledger. Returns Name Description updateWallets
nkruntime.WalletUpdateResult[] A list of wallet update results. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let updates : nkruntime.WalletUpdate [] = [
{
userId : '8f4d52c7-bf28-4fcf-8af2-1d4fcf685592' ,
changeset : {
coins : 10 , // Add 10 coins to the user's wallet.
gems : - 5 , // Remove 5 gems from the user's wallet.
},
metadata : {
gameResult : 'won' ,
}
}
];
let results : nkruntime.WalletUpdateResult [];
try {
results = nk . walletsUpdate ( updates );
} catch ( error ) {
// Handle error
}
walletUpdate
# Update a user's wallet with the given changeset.
Parameters Name Default Description userId
string
REQUIRED The ID of the user whose wallet to update. changeset
REQUIRED The set of wallet operations to apply. metadata
object Additional metadata to tag the wallet update with. updateLedger
bool false Whether to record this update in the ledger. Returns Name Description result
nkruntime.WalletUpdateResult The changeset after the update and before to the update, respectively. error
error An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let user_id = '8f4d52c7-bf28-4fcf-8af2-1d4fcf685592' ;
let changeset = {
coins : 10 , // Add 10 coins to the user's wallet.
gems : - 5 , // Remove 5 gems from the user's wallet.
};
let metadata = {
gameResult : 'won'
};
let result : nkruntime.WalletUpdateResult ;
try {
result = nk . walletUpdate ( user_id , changeset , metadata , true );
} catch ( error ) {
// Handle error
}