npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

quiz-api-client

v20.27.0

Published

Quiz API Client is a JavaScript Library with support in the browser and Node.js. We follow a standard RESTful model mirroring [restful.js](https://github.com/marmelab/restful.js) as well as including some of the quiz API's specific use cases.

Downloads

3,924

Readme

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' })

Pagination

Most Quiz API responses are limited to a page size of 50. To paginate through the results, call paginate:

const paginator = client.paginate('ResourceName', { additional: 'options' })
paginator.getPage(1) // fetches the records from the first page
paginator.totalPages // fetch at least one page before checking the total

To exhaustively fetch all records, page by page:

paginator.getAll()

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 QuizEntry extends ApiRecord {
  static schema() {
    return Joi.object().keys({
      entryEditable: Joi.boolean(),
      entryType: Joi.string().valid('Item', 'BankEntry', 'Bank', 'Stimulus'),
      id: Joi.string().required(),
      pointsPossible: Joi.number(),
      position: Joi.number().integer(),
      properties: Joi.object(),
      regradeAdjustedPointsPossible: Joi.number(),
      regradeAdjustedScoringData: Joi.object(),
      status: Joi.string().valid('mutable', 'immutable'),
      stimulusQuizEntryId: Joi.string(),
      cloneOfId: Joi.string()
    })
  }

  static methodsSupported() {
    return ['getAll', 'get', 'create', 'update', 'delete']
  }

  static resourceName() {
    return 'quiz_entries'
  }

  basePath({ quizId }) {
    return `/quizzes/${quizId}/${this.constructor.resourceName()}`
  }

  getActions() {
    return {
      clone: (fetcher, options) =>
        fetcher.post({ url: `${this.basePath(options)}/${this.data.id}/clone` })
    }
  }
}

module.exports = QuizEntry

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