Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@eroc/core

Package Overview
Dependencies
Maintainers
1
Versions
24
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@eroc/core

Lightweight framework for scalable applications

  • 3.0.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
0
decreased by-100%
Maintainers
1
Weekly downloads
 
Created
Source

core Build Status Coverage Status Code Climate

core is a concept introduced by Nicholas C. Zakas in this video

It helps you create scalable applications written in Javascript, giving you some structure and patterns to keep everything separated.

The Idea

Conceptually, everything in your application is a module, and your modules should work independently from each other, so if one module breaks, the others should not.

The central piece is the core.

A module should never talks directly to another module, for that you use a combination of listeners and notifications.

Getting Started

So let's think about the twitter page, and how we could re-build it using the core concept

Twitter Modules

Everything inside a red square is a module, they work independently.

Installing

npm i @eroc/core

Import

Raw import

import { Core, ALL, ERROR } from "./node_modules/@eroc/core/dist/core.es.js";

With node, rollup, webpack or parcel

import { Core, ALL, ERROR } from "@eroc/core";

With old NodeJs or Browserify

const { Core, ALL, ERROR } = require("@eroc/core/dist/core.umd.cjs");

Building modules

A module exports start and optionally a stop function.

export { start, stop };


const start = function (emitter) {
  return {};
};

const stop = function (instance) {
  // instance is what start returned
  // this allows to close open files, sockets, etc
};

To start this module in your core file:

import { Core } from "@eroc/core";
import * as exampleModule from "./exampleModule.js";

const core = new Core();
core.start(exampleModule);

Modules can only communicate via messages with other modules with the emitter received when start is called. It garantees that if a module tries to call something that doesn't exists or is broken, it won't break the module itself.

emitter.on(EVENT_NAME, function (data) {

});

emitter.emit(EVENT_NAME, { a: 7 });

To avoid spelling mistakes, import event names from a common file called eventNames.js.

Destroying modules

To stop a module use the method core.stop().

const exampleId = core.start(exampleModule);
core.stop(exampleId);

When you stop a module, the function stop will be called, if it exists.

Comunicating between modules

Now, thinking about Twitter, everytime you tweet something, it should appear on your tweet list right? but since our modules don't talk directly to each other, let's use the emitter.

Our tweet module should notify other modules that something has happened.

tweet.js
export { start };
import { NEW_TWEET } from "./eventNames.js";


const start = function(emitter) {
  // For the sake of simplicity, use an interval
  setInterval(function() {
    emitter.emit(NEW_TWEET,  {
      author: `Mauricio Soares`,
      text: `core is pretty #cool`
    });
  }, 5 * 1000)
};

Every 5 seconds, this module notifies everything that is listening to NEW_TWEET that something has happened. If nothing is listening to it, then nothing happens.

Our tweet-list is going to listen for this notifications.

tweet-list.js
export { start };
import { NEW_TWEET } from "./eventNames.js";


const start = function (emitter) {
  emitter.on(NEW_TWEET, (data) => {
      // do something with the data
  });
};

Cool right? If one of those modules stop working, then it will not break the other one!

API

Core

new Core()

Returns a new instance of core.

core.start(module, options)
  • module The module as a name-space ( import * as exampleModule from "./exampleModule.js" )
  • options optional object
    • name optional, String or Symbol that become moduleInstanceId

returns a promise that resolves with moduleInstanceId that can later be used to stop the module

const exampleInstanceId = await core.start(exampleModule);
core.stop(moduleInstanceId)
await core.stop(exampleInstanceId);
ALL

Constant to listen to all events

// listen for all events
core.on(ALL, ({ name, data, time }) => {
    const timeString = new Date(time).toISOString();
    console.debug(`${timeString} event ${String(name)} with data`, data);
});
ERROR

Constant to listen to most errors

// listen for errors
core.on(ERROR, ({ time, phase, error }) => {
    const timeString = new Date(time).toISOString();
    console.error(`Error during phase ${phase} at ${timeString}`, error);
});

logging

Optional logging to get started

useDefaultLogging(core, logger=console)
import { Core, useDefaultLogging } from "@eroc/core";


const core = new Core();

// listen for all events
useDefaultLogging(core);

eventRecorder

Utility to record all events. example

startEventRecorder(core)

returns an eventRecording. Access eventRecording.events to view all past events.

stopEventRecorder(core, eventRecording);

stops an eventRecording.

import { Core, useDefaultLogging } from "@eroc/core";


const core = new Core();
let eventRecording = startEventRecorder(core);
stopEventRecorder(core, eventRecording);

eventPlayer

Helper to replay events.

replayEvents(core, previousEvents, { sameSpeed = false })

Will replay previousEvents on core. previousEvents could come from eventRecording.events or from a database. Make sure to initialize modules before for it to have any effect. While events are replayed regulare event emits are disabled. This avoids duplicated events in case you emit events as a consequence of another event.

import { Core, replayEvents } from "@eroc/core";


const core = new Core();
// ... initialize modules
const events = // get events
replayEvents(core, events, { sameSpeed: true }); 

Maintainers

Contributing

  1. Fork core
  2. Create a topic branch - git checkout -b my_branch
  3. Change some files and git commit
  4. Push to your branch - git push origin my_branch
  5. Send a Pull Request

Testing

You need NodeJS installed on your machine

  1. npm i
  2. npm run bundle
  3. npm t

Changelog

3.0.0

  • Use abstract name to import for dependencies. Change default main. Convert to ES module.
  • Rename dist/core.umd.js into dist/core.umd.cjs

2.2.0

  • Add default logger

2.1.0

  • eventPlayer, eventRecorder optionals are importable directly from the core

2.0.0

  • core.start, core.stop return Promises
  • the module start and stop can return a promise
  • errors are emitted

1.1.0 introduce event recorder and player

1.0.0 stable release

0.15.0 major architecture change

2018-10-30 v0.13.0 remove deprecated startAll and stopAll

2018-10-29 v0.12.0 Drop bower and publish on npm

2018 Various changes

2015-06-15   v0.7.3   Refactor UMD

2015-05-14   v0.7.2   Hotfix with ID's

2015-02-15   v0.7.0   Deprecate Core.stopAll

2015-02-12   v0.6.0   Deprecate Core.startAll

2015-02-05   v0.5.0   Changes x to use in Sandbox

2015-01-17   v0.4.0   Add UMD

2015-01-15   v0.3.0   Ability to return values from init and destroy methods

2015-01-10   v0.2.1   Improve error messages

2014-12-30   v0.2.0   Isolation of DOM in modules

2014-12-21   v0.1.0   Release usable version

License

MIT License

Keywords

FAQs

Package last updated on 09 May 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc