Naturally Processed Meals
Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org »

quiz-api-client

13.5.0 • Public • Published

Quiz API Client

Quiz API Client is a JavaScript Library with support in the browser and Node.js. We follow a standard RESTful model mirroring restful.js as well as including some of the quiz API's specific use cases.

Initialization

The Quiz API client is initialized just like any class requiring only two arguments:

  • endpoint: The base endpoint of the API. You can supply config specific endpoints based on what environment you are end. (e.g. http://question.docker/api)
  • loadToken: A function that makes a request to your service to obtain a token. It is, currently, the responsibility of the consumer to determine which token is necessary for the call to succeed. This function call should return a promise with the token on success and an error on failure. The client will call it again should the first call fail, but will throw an error after that. The client will cache the token and recall in the event that it fails authorization.

Example

function loadToken() {
  return fetch('http://myservice.com/API/TO/TOKEN')
    .then(result => result.json())
    .then(({ token }) => token)
    .catch((err) => { throw err; });
}
 
const client = new QuizApiClient(
  'http://question.docker/api',
  loadToken
);
 
// client available to make requests

RESTful requests

The quiz API client provides an interface to follow most of the standard REST queries. The first parameter is always the name of the resource as a string. The last parameter is always an optional object to represent options to pass along. Each request returns a promise that will provide an instance (or array of instances) of the resource specified.

Get One

Performs a GET request with an id for the resource; it resolves to an instance of the resource.

Parameters:

  • Resource Name (string) - The name of the resource
  • id (int or string) - the id of the resource
  • options (object) optional - additional options to pass along

Example:

client.get('ResourceName', 4, { additional: 'options' })

Get All

Performs a GET request with no id and resolves all resources of that type.

Parameters:

  • Resource Name (string) - The name of the resource
  • options (object) optional - additional options to pass along

Example:

client.getAll('ResourceName', { additional: 'options' })

Create

Performs a POST request with no id and resolves to the new resource (with an identifier).

Parameters:

  • Resource Name (string) - The name of the resource
  • data (object) - content of the resource
  • options (object) optional - additional options to pass along

Example:

client.create('ResourceName', { title: 'Winnie the Pooh' }, { additional: 'options' })

Update

Performs a PUT request to update a specific resource and resolves to the updated resource.

Parameters:

  • Resource Name (string) - The name of the resource
  • id (int or string) optional - the id of the resource to update. If missing, it is assumed data will have a field, id.
  • data (object) - content of the resource
  • options (object) optional - additional options to pass along

Example:

client.update('ResourceName', 4,  { title: 'Winnie the Pooh' }, { additional: 'options' })
// or
client.update('ResourceName', { id: 4, title: 'Winnie the Pooh' }, { additional: 'options' })

Patch

Performs a PATCH request to patch a specific resource and resolves to the patched resource.

Parameters:

  • Resource Name (string) - The name of the resource
  • id (int or string) optional - the id of the resource to update. If missing, it is assumed data will have a field, id.
  • original (object) - original data of the object
  • data (object) - data to patch the original object
  • options (object) optional - additional options to pass along

Example:

client.patch('ResourceName', 4,  { title: 'Winnie the Pooh' }, { additional: 'options' })
// or
client.patch('ResourceName', { id: 4, title: 'Winnie the Pooh' }, { additional: 'options' })

Perform Action

The quiz API deviates from REST in a few cases, specifically when we wish to perform an action on a specific resource. We can do that with the performAction method.

Parameters:

  • Resource Name (string) - The name of the resource
  • original (object) - original data of the object
  • actionName (string) - name of the action to apply
  • options (object) optional - additional options to pass along

Example

In a quiz session, you can update the user's response, which makes a request through the kinesis stream.

client.performAction('QuizSession', { id: 4, ...}, 'userResponse', { sessionItem: {...}, userResponse: {...} })

Available Resources/Actions

Interested in adding resources/actions? Take a look at the records folder in this package. Every resource extends BaseRecord, and resources that connect to the server extend ApiRecord.

Creating a Resource

To create a new resource that connects to the server, extend ApiRecord. At its basic level, you will most likely need to update the following methods.

  • static schema() - returns a joi-browser object to build a schema to validate/sanitize data
  • static resourceName() - returns a string for the name of the resource to be used in URLs. More advanced URL schemes will override `basePath()
  • static methodsSupported() - returns an array of strings representing all methods supported. None are supported by default.

Example

const Joi = require('joi-browser')
const ApiRecord = require('../ApiRecord')
 
class ParticipantSession extends ApiRecord {
  static schema() {
    return Joi.object().keys({
      id: Joi.string().required(),
      multipleAttempts: Joi.object().required(),
      participantId: Joi.string().required(),
      userId: Joi.string().required(),
      quizApiQuizSessionId: Joi.string().required(),
      status: Joi.string().valid(['in_progress']),
      timezone: Joi.string().required(),
      createdAt: Joi.string()
    })
  }
 
  static methodsSupported() {
    return ['get', 'patch']
  }
 
  static resourceName() {
    return 'participant_sessions'
  }
}
 
module.exports = ParticipantSession

Creating an Action

Each resource has a getActions() method that returns an object mapping the name of the action to a function. The function has the following parameters:

  • fetcher - a reference to the libraries fetcher to make requests. See the util/Fetcher directory for more information.
  • options (object) optional - additional options to pass along

While the function can return anything, we strongly recommend returning a promise.

Example

In the following example, a quiz session has two actions: take and submit.

class QuizSession extends ApiRecord {
  // ...
 
  getActions() {
    return {
      take: fetcher =>
        fetcher
          .post({ url: `${this.basePath()}/${this.data.id}/take` })
          .then(body => new this.constructor(this.transformResponse(body)))
          .catch(err => {
            throw err
          }),
      submit: (fetcher, { sessionItemResponses }) =>
        fetcher
          .post({
            url: `${this.basePath()}/${this.data.id}/submit`,
            body: {
              session_item_responses: sessionItemResponses
            },
            noDecamelize: true
          })
          .then(body => new this.constructor(this.transformResponse(body)))
          .catch(err => {
            throw err
          })
    }
  }
}

Roadmap

The following is planned for future development.

  • Support for all Interaction Types
  • Internal management of different tokens scopes
  • Stronger schema validation mechanisms
  • Additional resource records that make things easier.

Keywords

none

install

npm i quiz-api-client

Downloadsweekly downloads

13

version

13.5.0

license

MIT

last publish

collaborators

  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
  • avatar
Report a vulnerability