svelte-websocket-store
v1.2.2
Published
svelte store with a websocket backend
Maintainers
Readme
svelte-websocket-store
Svelte store with a websocket backend
import websocketStore from "svelte-websocket-store";
const initialValue = { };
export const myStore = websocketStore("wss://mydomain.com/ws1", initialValue, ['option 1', 'option 2']);
// send JSON to websocket server
$myStore = { content: "to be saved", other_values: "all" };
// receive JSON from server (push)
let response = $myStore;API
Table of Contents
- active
- Key
- BaseRouter
- BaseTransition
- DetailRoute
- Entitlement
- Guard
- redirectGuard
- sequenceGuard
- parallelGuard
- websocketStore
- login
- handleFailedResponse
- MasterRoute
- nullGuard
- RootRoute
- SkeletonRoute
- ValueStoreRoute
- SessionData
- msecsRequiredForRefresh
- supportedTokenTypes
- Session
- decode
- Transition
- findClosestAttribute
- dispatchNavigationEvent
- nameValueStore
- WaitingGuard
active
- See: {Router.updateActive}
Keeps the node active state in sync.
Parameters
nodeElementrouterRouter
Key
Keys also act as svelte stores and can be subscribed.
export const article = derived(
[articles, router.keys.article],
([$articles, $id], set) => {
set($articles.find(a => a.id === $id));
return () => {};
}
);Type: Object
Properties
BaseRouter
Extends BaseTransition
key subscriptions:
const aKey = router.keys.aKey;
$aKey // fired if value of aKey changesParameters
routesArray<Route> all managed routesbasestring url (optional, defaultnew URL("../",import.meta.url).pathname)
Properties
linkNodesSet<Node> nodes having their active state updatedroutesArray<Route>keysObject collected keys of all routesparamsObject value mapping from keys (from current route)routeRoute currentnestedTransition ongoing nested transitionbasestring url
component
Current component. Either from a nested transition or from the current route
Returns SvelteComponent
value
Value if the current route
Returns any
path
Returns string url path with fragment & query
path
Replace current route.
Parameters
pathstring
replace
Replace current route without updating the state.
Parameters
pathstring
Returns Object former state
push
Leave current route and enter route for given path. The work is done by a Transition.
Parameters
pathstring where to go
Returns Transition running transition
finalizePush
Called from a Transition to manifest the new destination. If path is undefined the Transition has been aborderd.
Parameters
pathstring
continue
Continue a transition to its original destination. Shortcut for this.transition.continue(). If there is no transition ongoing and a fallbackPath is present, it will be entered. Otherwise does nothing.
Parameters
fallbackPathstring
abort
Abort a transition. Shortcut for this.transition.abort() If there is no transition ongoing and a fallbackPath is present it will be entered. Otherwise does nothing.
Parameters
fallbackPathstring
subscribe
Router subscription. Changes in the current route will trigger a update
Parameters
subscriptionFunction
updateActive
Update the active state of a node. A node is considered active if it shared the path prefix with the current route.
Parameters
nodeElement
addRoute
Add a new Route.
Parameters
routeRoute
routeFor
Find Route for a given value.
Parameters
valueany
Returns Route able to support given value
pathFor
Find path for a given value.
Parameters
valueanysuffixstring to be appended
Returns string path + suffix
BaseTransition
searchParams
Deliver url search params form the current location.
Returns URLSearchParams as extracted from the path
searchParams
Replaces the search part of the path with the given searchParams.
Parameters
searchParams(URLSearchParams | Object)
nest
Add another transition nesting level. Starts a transition from the given factory.
Parameters
pathstringfactoryTransition
continue
Continue a nested route to its original destination. Does nothing if the transition has not been nested.
abort
Abort the transition.
Parameters
error
Returns Promise<boolean> truen in case there was a nesten transition
DetailRoute
Extends ValueStoreRoute
Route to represent a slice of the masters list of values.
Properties
masterRoute route holding the master records
master
Route holding the list ov values
Returns Route our master
first
Returns Promise<any> 1st. entry
last
Returns any last entry
previous
Returns any previous value
next
Returns Promise<any> next value
Entitlement
Parameters
Guard
Enforces conditions of routes Like the presents of values in the context
enter
Called while entering a route (current outlet is not yet set)
Parameters
transitionTransition
leave
Called before leaving a route
Parameters
transitionTransition
redirectGuard
Redirects to a given path if condition is met.
Parameters
sequenceGuard
Execute guards in a sequence.
Parameters
childrenIterable<Guard>
parallelGuard
Execute guards in a parallel.
Parameters
childrenIterable<Guard>
websocketStore
Create a writable store based on a web-socket. Data is transferred as JSON. Keeps socket open (reopens if closed) as long as there are subscriptions.
Parameters
urlstring the WebSocket urlinitialValueany store value used before 1st. response from server is presentsocketOptionsArray<string> transparently passed to the WebSocket constructor
Returns Store
login
Bring session into the valid state by calling the authorization endpoint and asking for a access_token. Executes a POST on the endpoint url expecting username, and password as json
Parameters
sessionSession to be openedendpointstring authorization urlusernamestring id of the userpasswordstring user credentialstokenmapObject token names in response to internal known values (optional, defaultdefaultTokenMap)
Returns Promise<(string | undefined)> error message in case of failure or undefined on success
handleFailedResponse
Extract error description from response.
Parameters
responseResponse
MasterRoute
Extends SkeletonRoute
Route holding a ordered collection of values.
Parameters
pathoptions
Properties
valueArray<any>
nullGuard
Default empty guard does nothing.
RootRoute
Route at the root of the tree. This route has no parent. All other routes are below of this one.
hasParams
Are there parameters in the path.
Returns boolean true if route has parameters (:key)
path
Returns string empty as we are the root
propertyMapping
Returns Object empty object
guard
Returns Guard empty guard which does nothing
SkeletonRoute
Extends RootRoute
Route Subscriptions on Routes fire when the route value changes.
Parameters
pathoptions(optional, default{})
Properties
pathstring full path of the Route including all parentscomponentSvelteComponent target to showlinkComponentSvelteComponent content for ObjectLinkpropertyMappingObject Map properties to object attributes Keys are the property names and values are the keys in the resulting object.prioritynumberkeysArray<string> as found in the pathregexRegExvalueany
enter
Enter the route from a former one. All parent routes up to the common ancestor are entered first.
Parameters
transitionTransitionuntilRouteRoute the common ancestor with the former route
leave
Leave the route to a new one. All parent routes up to the common ancestor are left.
Parameters
transitionTransitionuntilRouteRoute the common ancestor with the future route
isAcceptable
Check if value and properties are acceptable for the route.
Parameters
valueany to be placed into routepropertiesObject as presented in the route
Returns boolean true if value can be accepted
propertiesFor
Extract properties from a value. All property values must be strings.
Parameters
valueany source of the properties
Returns (Object | undefined) properties extracted from given value
commonAncestor
Find common ancestor with an other Route.
Parameters
otherRoute
Returns (Route | undefined) common ancestor Route between receiver and other
valueFor
Deliver value for a given set of properties of the transition. Default implemantation asks the parent route.
Parameters
transitionTransition
Returns any for matching properties
value
Deliver route value. Default implemantation asks the parent route.
Returns any
propertyMapping
Deliver property mapping. Default implemantation asks the parent route.
Returns Object for matching properties
objectInstance
Default implemantation asks the parent route.
ValueStoreRoute
Extends SkeletonRoute
Route holding a single value
SessionData
Data as preserved in the backing store.
Type: Object
Properties
msecsRequiredForRefresh
Time required to execute a refresh
Type: number
supportedTokenTypes
Session
User session. To create as session backed by browser local storage.
let session = new Session(localStorage);or by browser session storage
let session = new Session(sessionStorage);Parameters
storeSessionData (optional, defaultlocalStorage)
Properties
entitlementsSet<string>subscriptionsSet<Object> store subscriptionsexpirationDateDate when the access token expiresaccess_tokenstring token itselfrefresh_tokenstring refresh token
update
Consume auth response data and reflect internal state.
Parameters
dataObject
refresh
Refresh with refresh_token.
Returns Promise<boolean> true if refresh was succcessfull false otherwise
authorizationHeader
Http header suitable for fetch.
Returns Object header The http header.
Returns string header.Authorization The Bearer access token.
isValid
As long as the expirationTimer is running we must be valid.
Returns boolean true if session is valid (not expired)
invalidate
Remove all tokens from the session and the backing store.
hasEntitlement
Check presence of an entitlement.
Parameters
namestring of the entitlement
Returns boolean true if the named entitlement is present
subscribe
Fired when the session changes.
Parameters
subscriptionFunction
decode
Extract and decode the payload.
Parameters
tokenstring
Returns Object payload object
Transition
Extends BaseTransition
Transition between routes.
Parameters
routerRouterpathstring new destination
Properties
routerRouterpathstring new destination
start
Start the transition
- leave old route
- find matching target route @see matcher()
- enter new route
- set params
- set current route
end
- See: Router.finalizePush
Cleanup transition. Update Nodes active state
redirect
Halt current transition and go to another route. To proceed with the original route call continue() The original transition will keept in place and can be continued afterwards.
Parameters
pathstring new route to enter temporary
abort
Bring back the router into the state before the transition has started. All nested transitions also will be termniated.
Parameters
e(Exception | undefined)
findClosestAttribute
Walks up the dom tree parents unti a node with a given attribute is found or the root node is reached.
Parameters
dispatchNavigationEvent
Dispatches a NAVIGATION_EVENT with pathname and hash
Parameters
eventEvent
nameValueStore
Create a named object which also acts as a store.
Parameters
namestringvalueany initial value
Properties
valueany
Returns Store
WaitingGuard
Extends Guard
Shows a component during transition.
Parameters
componentSvelteComponent to show up during th transitionrampUpTimenumber initial delay for the componnt to show up (optional, default300)
install
With npm do:
npm install svelte-websocket-storeWith yarn do:
yarn add svelte-websocket-storerun tests
export BROWSER=safari|chrome|...
npm|yarn testlicense
BSD-2-Clause
