TypeSafeSession

public protocol TypeSafeSession : TypeSafeMiddleware, Decodable, Encodable

A TypeSafeMiddleware for managing user sessions. The user defines a final class with the fields they wish to use within the session. This class can then save or destroy itself from a static Store, which is keyed by a sessionId. The sessionId can be extracted from the session cookie to initialise an instance of the user’s class with the session data. If no store is defined, the session will default to an in-memory store.

Usage Example:

In this example, a class conforming to the TypeSafeSession protocol is defined containing an optional “name” field. Then a route on “/session” is set up that stores a received name into the session.

final class MySession: TypeSafeSession {
   var name: String?

   let sessionId: String
   init(sessionId: String) {
       self.sessionId = sessionId
   }
    static var store: Store?
    static let sessionCookie = SessionCookie(name: "session-cookie", secret: "abc123")
}

router.post("/session") { (session: MySession, name: String, respondWith: (String?, RequestError?) -> Void) in
   session.name = name
   try? session.save()
   respondWith(session.name, nil)
}

Note: When using multiple TypeSafeSession classes together, if the cookie names are the same, the cookie secret must also be the same. Otherwise the sessions will conflict and overwrite each others cookies. (Different cookie names can use different secrets).

Static type properties

  • Specifies the Store for session state, or leave nil to use a simple in-memory store. Note that in-memory stores do not provide support for expiry so should be used for development and testing purposes only.

    Declaration

    Swift

    static var store: Store? { get set }
  • A SessionCookie that defines the session cookie’s name and attributes.

    Declaration

    Swift

    static var sessionCookie: SessionCookie { get }

Mandatory instance properties

  • The unique id for this session.

    Declaration

    Swift

    var sessionId: String { get }
  • Create a new instance (an empty session), where the only known value is the (newly created) session id. Non-optional fields must be given a default value.

    Existing sessions are restored via the Codable API by decoding a retrieved JSON representation.

    Declaration

    Swift

    init(sessionId: String)

Functions implemented in extension

  • save(callback:) Default implementation

    Save the current session instance to the store. This also refreshes the expiry.

    Default Implementation

    Save the current session instance to the store.

    Usage Example:

    router.post("/session") { (session: MySession, name: String, respondWith: (String?, RequestError?) -> Void) in
        session.name = name
        session.save()
        respondWith(session.name, nil)
    }
    

    Declaration

    Swift

    func save(callback: @escaping (Error?) -> Void)

    Parameters

    callback

    A callback that will be invoked after saving to the store has been attempted, with a parameter describing the error (if one occurred). Any such error will be logged for you, so if you do not want to perform further processing or logic based on the success of this operation, this parameter can be omitted.

  • destroy(callback:) Default implementation

    Destroy the session, removing it and all its associated data from the store.

    Default Implementation

    Destroy the session, removing it and all its associated data from the store.

    Usage Example:

    router.delete("/session") { (session: MySession, respondWith: (RequestError?) -> Void) in
        session.destroy()
        respondWith(nil)
    }
    

    Declaration

    Swift

    func destroy(callback: @escaping (Error?) -> Void)

    Parameters

    callback

    A callback that will be invoked after removal from the store has been attempted, with a parameter describing the error (if one occurred). Any such error will be logged for you, so if you do not want to perform further processing or logic based on the success of this operation, this parameter can be omitted.

  • touch(callback:) Default implementation

    Refreshes the expiry of a session in the store. Note that this is done automatically when a session is restored from a store, but could be repeated if needed (for example, if the processing of a handler takes a long time and it is desirable to refresh the expiry before sending the response).

    Default Implementation

    Touch the session, refreshing its expiry time in the store.

    Declaration

    Swift

    func touch(callback: @escaping (Error?) -> Void)

    Parameters

    callback

    A callback that will be invoked after updating the store has been attempted, with a parameter describing the error (if one occurred). Any such error will be logged for you, so if you do not want to perform further processing or logic based on the success of this operation, this parameter can be omitted.

  • Static handle function that will try and create an instance of Self. It will check the request for the session cookie. If the cookie is not present it will create a cookie and initialize a new session for the user. If a session cookie is found, this function will decode and return an instance of itself from the store.

    Declaration

    Swift

    public static func handle(request: RouterRequest, response: RouterResponse, completion: @escaping (Self?, RequestError?) -> Void)

    Parameters

    request

    The RouterRequest object used to get information about the request.

    response

    The RouterResponse object used to respond to the request.

    completion

    The closure to invoke once middleware processing is complete. Either an instance of Self or a RequestError should be provided, indicating a successful or failed attempt to process the request.