Created
August 17, 2017 20:50
-
-
Save mbalex99/322f080f415fea7b3a8ff4913e8243e1 to your computer and use it in GitHub Desktop.
Ticker File Example with Faker and Realm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Server } from './' // import { Server } from 'realm-object-server' | |
import * as faker from 'faker' | |
import * as Realm from 'realm' | |
const myNewServer = new Server({ | |
port: 9081 | |
}) | |
myNewServer.start() | |
.then(() => { | |
console.log('Started! on port 9081') | |
getStarted() | |
}); | |
const TickerSchema: Realm.ObjectSchema = { | |
name: 'Ticker', | |
primaryKey: 'tickerSymbol', | |
properties: { | |
tickerSymbol: { type: 'string', optional: false }, | |
price: { type: 'float', optional: false }, | |
companyName: { type: 'string', optional: false }, | |
} | |
} | |
function generateRandomTickerSymbol(len: number, charSet: string = null) { | |
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
let randomString = ''; | |
for (let i = 0; i < len; i++) { | |
let randomPoz = Math.floor(Math.random() * charSet.length); | |
randomString += charSet.substring(randomPoz, randomPoz + 1); | |
} | |
return randomString; | |
} | |
function getStarted() { | |
Realm.Sync.User.login(`http://127.0.0.1:9081`, 'sampleuser', 'samplepassword', async (error, user) => { | |
if (error) { | |
console.log(`Error logging in: ${error}`) | |
return | |
} | |
let realm = await Realm.open({ | |
sync: { | |
url: `realm://127.0.0.1:9081/tickers`, | |
user: user | |
}, | |
schema: [TickerSchema], | |
}) | |
let tickerResults = realm.objects('Ticker') | |
if (tickerResults.length === 0) { | |
realm.write(() => { | |
for (let index = 0; index < 100; index++) { | |
realm.create('Ticker', { | |
tickerSymbol: generateRandomTickerSymbol(3), | |
price: faker.random.number({ min: 20, max: 2000 }), | |
companyName: faker.company.companyName() | |
}, true) | |
} | |
}) | |
} | |
setInterval(() => { | |
const randomTicker = tickerResults[Math.floor(Math.random() * tickerResults.length)] | |
realm.write(() => { | |
randomTicker["price"] = faker.random.number({ min: 20, max: 2000 }) | |
}) | |
}, 50) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment