Примеры кода — Torin Asakura

Примеры кода

  • GraphQL -> Apollo

    
    class ApiClient extends EventEmitter {
      constructor() {
        super()
        const networkInterface = createNetworkInterface({ uri: process.env.API_URL })
        networkInterface.use([{
          applyMiddleware: this.applyMiddleware,
        }])
        networkInterface.useAfter([{
          applyAfterware: this.applyAfterware,
        }])
        this.client = new ApolloClient({
          networkInterface,
        })
      }
      applyMiddleware = (req, next) => {
        const token = this.token
        if (!req.options.headers) {
          req.options.headers = {}
        }
        if (token) {
          req.options.headers.authorization = token
        }
        next()
      }
      applyAfterware = ({ response }, next) => {
        if (response.status === 401) {
          this.emit('logout')
        }
        next()
      }
      setToken(token) {
        this.token = token
      }
      async load() {
        const { data } = await this.client.query({
          query: gql`
            query {
              user {
                id
                email
                firstName
                lastName
                balance
                salesBalance
                inviteCode
                referals
                status
                activations {
                  id
                  status
                  startAt
                  leftTime
                  createdAt
                  servicePlan {
                    type
                    period
                    time
                  }
                }
              }
              servicePlans {
                type
                period
                time
                price
                profitabilityPerDay
                profitabilityPerHour
                amount
                memory
                cpu
              }
            }
          `,
        })
        return data
      }
    }
    
    
  • Electron -> Composite App Logic

    
    class Application {
      constructor() {
        this.protocolHandler = new ProtocolHandler()
        this.ipcManager = new IpcManager()
        this.apiClient = new ApiClient()
        this.settings = new Settings()
        this.tray = new Tray()
        this.scheduler = new Scheduler()
        this.windows = {
          auth: new AuthWindow(),
          main: new MainWindow(),
        }
        this.ipcManager.on('login', this.onLogin)
        this.ipcManager.on('logout', this.onLogout)
        this.ipcManager.on('schedule:save', this.onScheduleSave)
        this.ipcManager.on('session:start', this.onSessionStart)
        this.ipcManager.on('session:stop', this.onSessionStop)
        this.apiClient.on('logout', this.onLogout)
        this.tray.on('open', this.onOpenPage)
        this.tray.on('quit', this.quit)
        this.scheduler.on('stat', this.onSessionStat)
        this.scheduler.on('started', this.onSessionStarted)
        this.scheduler.on('stopped', this.onSessionStoped)
        this.scheduler.on('tick', this.onSessionTick)
        this.scheduler.on('wait', this.onSessionWait)
        app.on('window-all-closed', this.onWindowAllClosed)
      }
      async start() {
        this.protocolHandler.register()
        this.ipcManager.init()
        await this.settings.load()
        await this.launch()
      }
      async launch() {
        if (!this.settings.getToken()) {
          await this.windows.auth.open()
          return null
        }
        await this.windows.main.open()
        this.apiClient.setToken(this.settings.getToken())
        const { user, servicePlans } = await this.apiClient.load()
        this.settings.setUser(user)
        this.settings.setServicePlans(servicePlans)
        await this.settings.loadMachineId()
        if (this.settings.isActivated()) {
          await this.settings.sync()
        }
        this.windows.main.send('init', this.settings.toJSON())
        if (this.settings.isActivated()) {
          this.tray.add()
          if (this.settings.isStarted()) {
            this.scheduler.setSchedules(this.settings.getSchedules())
            this.scheduler.setMachineId(this.settings.getMachineId())
            this.scheduler.setToken(this.settings.getToken())
            await this.scheduler.start()
          }
        }
        return null
      }
      quit() {
        app.quit()
      }
      onWindowAllClosed = () => {
        if (!this.settings.isActivated()) {
          this.quit()
        }
      }
      onLogin = async (token) => {
        this.settings.setToken(token)
        await this.settings.save()
        await this.windows.auth.hide()
        await this.launch()
        await this.windows.auth.close()
      }
      onLogout = async () => {
        this.settings.setToken(null)
        await this.settings.save()
        await this.windows.main.hide()
        await this.launch()
        await this.windows.main.close()
        this.scheduler.stop()
        this.tray.destroy()
      }
      onOpenPage = async (target) => {
        if (this.windows.main.isClosed()) {
          await this.windows.main.open()
          this.windows.main.send('init', this.settings.toJSON())
        }
        if (this.windows.main.isMinimized()) {
          this.windows.main.restore()
        }
        this.windows.main.send('location:change', target)
      }
      onScheduleSave = async (schedules) => {
        this.settings.setSchedules(schedules)
        await this.settings.save()
        if (this.settings.isStarted()) {
          this.scheduler.setSchedules(schedules)
          this.scheduler.setMachineId(this.settings.getMachineId())
          this.scheduler.setToken(this.settings.getToken())
          this.scheduler.refresh()
        }
        this.windows.main.send('schedule:saved')
      }
      onSessionStart = async () => {
        this.settings.setStarted(true)
        await this.settings.save()
        this.scheduler.setSchedules(this.settings.getSchedules())
        this.scheduler.setMachineId(this.settings.getMachineId())
        this.scheduler.setToken(this.settings.getToken())
        await this.scheduler.start()
      }
      onSessionStop = async () => {
        this.settings.setStarted(false)
        await this.settings.save()
        this.scheduler.stop()
      }
      onSessionStat = (data) => {
        this.windows.main.send('session:stat', data)
      }
      onSessionStarted = (data) => {
        this.windows.main.send('session:started', data)
      }
      onSessionStoped = () => {
        this.windows.main.send('session:stopped')
      }
      onSessionTick = (data) => {
        this.windows.main.send('session:tick', data)
      }
      onSessionWait = (data) => {
        this.windows.main.send('session:wait', data)
      }
    }
    
    
  • Python/Django -> AsyncIO/AIORedis

    
    async def conn(socket, *a):
        try:
            await auth(socket)
        except websockets.exceptions.ConnectionClosed:
            pass
        if hasattr(socket, 'user'):
            if not socket.user in sockets:
                sockets[socket.user] = []
            sockets[socket.user].append(socket)
            users[socket.user]['online'] = True
            await send(socket, 'me', socket.user, users[socket.user])
            await info('status', socket.user, True)
            index = users[socket.user]['group'] != 'dev' and 1 or 0
            await send(socket, 'update', 'groups', groups[index:])
            data = []
            for key, val in users.items():
                if key != socket.user:
                    res = {'email': key, 'order': float(val['created_at'])}
                    for attr in ('name', 'group', 'online'):
                        res[attr] = val.get(attr, False)
                    chat = await Chat(socket, {'user': key}).reg()
                    data.append(await book(chat, socket.user, res))
            for key, val in channels.items():
                if not val['users'] or socket.user in val['users']:
                    res = {'token': key, 'order': float(val['created_at'])}
                    for attr in ('name', 'desc', 'group'):
                        res[attr] = val[attr]
                    data.append(await book('channel:messages:' + key, socket.user, res))
            await send(socket, 'update', 'users', sorted(
                data, reverse=True, key=lambda user: user['order']))
            while True:
                try:
                    data = await socket.recv()
                    if data.startswith('+'):
                        (scope, method) = ('file', 'upload')
                        finish = data[1] == '!'
                        split = data[2:].split(':')
                        data = {'pk': split[0]}
                        data['chunk'] = ':'.join(split[1:])
                        data['finish'] = finish
                    else:
                        data = json.loads(data)
                        (scope, method) = data['method'].split('-')
                    read = getattr(api.get(scope)(socket, data), method)
                    asyncio.ensure_future(read())
                except websockets.exceptions.ConnectionClosed:
                    await shut(socket)
                    break
    
    

Instagram

Twitter

Москва и МО

Якутск