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

@aims-api/aims-tagging-node

v0.0.8

Published

A client package for AIMS Tagging API

Downloads

685

Readme


Getting Started

npm install @aims-api/aims-tagging-node

Authentication

In order to use the lirbary you need to obtain credentials by contacting us at [email protected]. Credentials consist of CLIENT_ID, CLIENT_SECRET, LOGIN and PASSWORD.

To access protected routes you need to authenticate in order to get a time-limited token. You need to use this token while creating a client instance.

Example with Next.js

It is common to make a proxy request from client app to the server "Next.js API route" in order to hide foreign URL.

You may store the token in a cookie or local storage (browser), but you need to retrieve it from the request object. Storing the token in cookies is recommended for security reasons. In case you decide to store it in cookies, you can set Axios interceptor to check if cookie is still valid and if not, terminate user session in order to obtain a new token.

// pages/api/authenticate.ts

import { NextApiRequest, NextApiResponse } from 'next'
import { Client as TaggingApiClient } from '@aims-api/aims-tagging-node'

export const createClient = async (req: NextApiRequest) => {
  const { clientId, clientSecret } = await getSiteConfigForRequest(req)
  const apiUserToken = getTokenFromCookie(req)

  // You can retrieve auth_token from cookies or local storage
  // Authentication endpoints (e.g. "authenticate", "register", ...)
  // do not require "apiUserToken" field
  return new TaggingApiClient({
    apiHost: 'HOST_URL', // optional
    clientId: 'YOUR_CLIENT_ID', // required
    clientSecret: 'YOUR_CLIENT_SECRET', // required
    apiUserToken: JSON.parse(req.cookies.auth_token),
  })
}

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  if (req.method === 'POST') {
    try {
      const { userEmail, userPassword } = req.body // credentials: LOGIN, PASSWORD
      // passed from the client-side code
      const aimsClient = createClient(req)
      const response = await aimsClient.endpoints.authentication.authenticate({
        userEmail,
        userPassword,
      })

      const { token, ...rest } = response // removes token from the response to hide
      // from the client-side code (optional)
      return
      res
        .setHeader(
          'Set-Cookie',
          `auth_token=${JSON.stringify(response.token)}; HttpOnly; Secure; path=/`,
        ) // sets token to cookie (optional)
        .status(200)
        .json(rest)
    } catch (error) {
      console.warn(error)
    }
  }
  return res.status(400).json('Method not allowed')
}

export default handler

Usage

When you create a client instance in your codebase, you can then easily access all the existing endpoints via IDE autocomplete, as well as the required and optional parameters.

It's recommended to create a new file for each request handler.

For calling an endpoint batch.startTagging credits are required, for each track in a batch user needs to have exactly one credit. To get information about credits availability, please call apiUser.remainingMonthlyRequests endpoint, property is named remainingMonthlyRequests.

TypeScript

You can import input and response types that are provided in every endpoint file. In order to validate response structure and prevent application from crashing, you may use Zod library.

Example

// src/types/index.ts

...

type Track = Partial<{
  id: string
  title: string
  tags: Tags | null
  filesize: number | null
  duration: number | null
  processedAt: DateTime | null
  hookUrl: string | null
  modelVersion: string
  queuedAt: DateTime | null
  batchId: string | null
}>

Routes

The library provides a set of endpoints that can be found in src/client/index.ts file by the endpoints property on line #175.

Response Structure

Responses are not validated by this library, therefore you need to parse the structure on your own, referring to provided response types. If you find any incosistency, please open an issue or contact us via email.

All endpoints excerpt userData object that contains remainingRequests property, the value is an integer (of type String) that represents the number of credits available for tagging. To access exact response data in the client-side code you need to read response.data.data.

type ResponseType = {
  data: any
  userData: {
    remainingRequests: string
  }
}

This library uses Axios under the hood to make requests, so any network error will be of type AxiosError. Please, check Axios documentation for more information.

Example of parsing an error with Zod on the client side:

// src/helpers/response.ts

import { z } from 'zod'
import { isAxiosError } from 'axios'

interface CustomError {
  status: number | null
  message: string
  field?: string
}

const errorSchema = z.object({
  status: z.number(),
  message: z.string(),
  field: z.optional(z.string()),
})

const notParsed: CustomError = {
  status: 500,
  message: 'Not able to parse error',
}

export const parseError = (error: unknown) => {
  if (isAxiosError(error) && error.response !== undefined) {
    const errorParserResponse = errorSchema.safeParse(error.response.data)
    if (!errorParserResponse.success) {
      return notParsed
    }
    return errorParserResponse.data
  }
  return notParsed
}

License

See LICENSE for more information.