Syncano Server-side Library
This library supposed to be used in Syncano Sockets (inside scripts)
to communicate with Syncano Core Services. Syncano provides various Core Services:
- Database (db) - NoSQL database to store your application data
- Users Management (users) - service to store and manage users and groups of your application
- Event Loop (events) - service to emit events which can be caught by any Socket
- Realtime Channels (channels) - implement publish/subscribe model for realtime communication
Library initialization
To initialize library simply type:
import { data, users, socket, response, event, logger } from 'syncano-server'
Library initiated that way will grab necessary information from the context of you Socket Script - it means that you don't need to provide additional information such as Instance name or authentication key (token) to your Instance.
If you want to force the library to connect to specified instance type:
import Server from 'syncano-server'
const { data, events } = new Server({
token: '9-12jdiasdnfo23nrokms',
instanceName: 'example-instance-name'
})
Examples
Using Database (data)
In this example tags
is a name of a class (data model) configured for that instance.
data.tags
.create({
name: 'javascript',
usage_count: 0
})
.then(tag => {});
data.tags
.where('usage_count', 'gt', 100)
.take(140)
.list()
.then(tags => {})
data.posts
.where('author.email', 'john@example.com')
.list()
.then(posts => {})
data.posts
.with('author')
.list()
.then(posts => {})
data.tags.delete([8735, 8733])
data.tags.delete(7652)
Managing users (users)
users
.where('email', 'john.doe@example.com')
.first()
.then(user => {
})
users
.where('email', 'john.doe@example.com')
.firstOrFail()
.then(user => {})
.catch(err => {
})
Using Events (events)
event.emit('my_signal', {dummyKey: 'dummy_value'})
.then(event => {})
.catch(err => {
})
Publishing to channels
channel.publish('my_channel', {dummyKey: 'dummy_value'})
.then(res => {})
.catch(err => {})
Socket connection
const latestTags = await socket.get('tags/list', { sort: 'latest' })
const createdTag = await socket.post('tags/create', { name: 'nature' })
HTTP Responses
response('Hello world')
response('Hello world', 200, 'text/plain', {
'X-RATE-LIMIT': 50
})
response
.header('X-RATE-LIMIT', 50)
.header('X-USAGE', 35)
('Check headers')
response.json({
title: "Post title",
content: "Lorem ipsum dolor sit amet."
})
response
.header('X-RATE-LIMIT', 50)
.json({
title: "Post title",
content: "Lorem ipsum dolor sit amet."
})
Logging
For debug purposes you can use logger
:
Example:
import {logger} from 'syncano-server'
logger.listen(event => {
})
logger.levels(['error', 'notice', 'fatal'])
const log = logger('User Socket')
log.error('This is error message!')
log.warn('This is warning message!')
log.info('This is info message!', {hello: "world"})
log.debug('This is debug message!')
Check documentation to learn more.