新书节点JS SDK
FreshBooks NodeJS SDK允许您更方便地使用FreshBooks API.
安装
使用您最喜欢的软件包管理器安装任何软件包并保存到您的 package.json数字 :
$ npm install @freshbooks/api
# Or, if you prefer yarn
$ yarn add @freshbooks/api
使用量
见 完整文档。 。 。 .
配置 API 客户端
您的应用程序将使用 REST API 进行交互 Client 对象,可从 @freshbooks/api 软件包.
客户端可立即使用有效的 OAuth 令牌,或提供客户端秘密,并重定向 URI
然后用来获取访问令牌.
使用预生成的访问符
import { Client } from '@freshbooks/api'
const clientId = process.env.FRESHBOOKS_APPLICATION_CLIENT_ID
// Get token from authentication or configuration
const token = process.env.FRESHBOOKS_TOKEN
// Instantiate new FreshBooks API client
const client = new Client(clientId, {
accessToken: token,
})
使用客户端秘密并重定向 URI
import { Client } from '@freshbooks/api'
const clientId = process.env.FRESHBOOKS_APPLICATION_CLIENT_ID
const clientSecret = process.env.FRESHBOOKS_APPLICATION_CLIENT_SECRET
// Instantiate new FreshBooks API client
const client = new Client(clientId, {
clientSecret,
redirectUri: 'https://your-redirect-uri.com/'
})
// Give this URL to the user so they can authorize your application
const authUrl = client.getAuthRequestUrl()
// This will redirect them to https://your-redirect-uri.com/?code=XXX
const code = ...
// Returns an object containing the access token, refresh token, and expiry date
// Note that this function sets the token on this client instance to automatically
// authenticates all future requests with this client instance
const tokens = client.getAccessToken(code)
从 REST API 获取/ 设置数据
所有 REST API 方法都以 :
{
ok: boolean
data?: T // model type of result
error?: Error
}
示例 API 客户端呼叫 :
try {
// Get the current user
const { data } = await client.users.me()
console.log(`Hello, ${data.id}`)
} catch ({ statusCode, message }) {
// Handle error if API call failed
console.error(`Error fetching user: ${statusCode} - ${message}`)
}
错误
如果 API 出错, 响应对象包含 error 对象,形状如下:
{
name: string // Name of the method called
message: string // Error message
statusCode?: string // HTTP Status Code
errors?: APIError[] // More detailed message if available
}
并非所有API都调用返回特定错误的列表,但如果调用,其形式将是:
{
message: string // Specific error message eg. 'Item not found.'
errorCode?: number // A error code, if available. Eg. '1012'
field?: string // The field that caused the error, if available. Eg. `itemid`
object?: string // The resource, if available. Eg. `item`
value?: string // The value of the field, if available. Eg. `123432`
}
实例:
clientData = {}
try {
const client = await fbClient.clients.single(accountId, 00000)
console.log('Not called')
} catch (err) {
console.log(err.name)
console.log(err.message)
console.log(err.statusCode)
console.log(err.errors)
}
/*
Output:
Get Client
Client not found.
404
[
{
message: 'Client not found.',
errorCode: 1012,
field: 'userid',
object: 'client',
value: '00000'
}
]
*/
clientData = {}
try {
const client = await fbClient.clients.create(clientData, accountId)
console.log('Not called')
} catch (err) {
console.log(err.name)
console.log(err.message)
console.log(err.statusCode)
console.log(err.errors)
}
/*
Output:
Create Client
At least one field among fname, lname, email and organization is required.
422
[
{
message: 'At least one field among fname, lname, email and organization is required.',
errorCode: 7012,
field: null,
object: 'client',
value: ''
}
]
*/
铺设、过滤和包括
如果一个端点通过查询参数支持搜索或自定义包含,这些参数
可用 QueryBuilderType。见 FreshBooks API - 参数
文档.
type QueryBuilderType = PaginationQueryBuilder | IncludesQueryBuilder | SearchQueryBuilder
API客户端上的适当方法将支持一系列构建者:
public readonly invoices = {
list: (accountId: string, queryBuilders?: QueryBuilderType[]) => Promise<Result<{
invoices: Invoice[];
pages: Pagination;
}>>;
}
倾斜
植入结果包含在 list 回应。 这个 data 对象将包含 pages 财产,包括:
{
page: number // The current page of results
pages: number // The number of pages of results
total: number // The total number of results
size: number // The number of results per page
}
为了打通电话,首先创建一个 PaginationQueryBuilder 使用 page 财务报告和审定财务报表 perPage 函数
并传入 list 电话.
import { PaginationQueryBuilder } from '@freshbooks/api/dist/models/builders/PaginationQueryBuilder'
const paginator = new PaginationQueryBuilder()
paginator.page(1).perPage(10)
let page = 1
let totalPages = 1
while (page <= totalPages) {
let response = await fbClient.clients.list(accountId, [paginator])
let { clients, pages } = response.data
console.log(clients)
console.log(`Page ${pages.page} of ${pages.pages} pages`)
console.log(`Showing ${pages.size} per page for ${pages.total} total clients`)
page++
totalPages = pages.pages
paginator.page(page)
console.log('Clients:')
clients.map((client) => console.log(client.organization))
}
搜索过滤器
过滤返回的结果 list 方法调用,构建一个 SearchQueryBuilder 传过来,传进去
页:1 list 电话.
这个 SearchQueryBuilder 支持模式 : equals, (中文(简体) ), in, (中文(简体) ), like, (中文(简体) ), between,以及 boolean。 。 。 .
s = SearchQueryBuilder()
s.in("email", "[email protected]")
console.log(s.build()) // "&search[email][email protected]"
s = SearchQueryBuilder()
s.in("clientids", [123, 456])
console.log(s.build()) // "&search[clientids][]=123&search[clientids][]=456"
s = SearchQueryBuilder()
s.like("email_like", "@freshbooks.com")
console.log(s.build()) // "&search[email_like][email protected]"
s = SearchQueryBuilder()
s.between("amount", 1, 10)
console.log(s.build()) // "&search[amount_min]=1&search[amount_max]=10)"
s = SearchQueryBuilder()
s.between("start_date", date.today())
console.log(s.build()) // "&search[start_date]=2020-11-21"
s = SearchQueryBuilder()
// Boolean filters are mostly used on Project-like resources
s.boolean('complete', false) // "&complete=false"
示例 API 客户端调用 SearchQueryBuilder数字 :
import { SearchQueryBuilder } from '@freshbooks/api/dist/models/builders/SearchQueryBuilder'
//create and populate SearchQueryBuilder
const searchQueryBuilder = new SearchQueryBuilder()
.like('address_like', '200 King Street')
.between('date', { min: new Date('2010-05-06'), max: new Date('2019-11-10') })
try {
// Get invoices matching search query
const { data } = await client.invoices.list(accountId, [searchQueryBuilder])
console.log('Invoices: ', data)
} catch ({ statusCode, message }) {
// Handle error if API call failed
console.error(`Error fetching user: ${statusCode} - ${message}`)
}
包括
将额外关系、分资源或数据纳入答复 IncludesQueryBuilder 可构建
然后可以传入 list, (中文(简体) ), single, (中文(简体) ), create,以及 update 打电话.
示例 API 客户端调用 IncludesQueryBuilder数字 :
import { IncludesQueryBuilder } from '@freshbooks/api/dist/models/builders/IncludesQueryBuilder'
//create and populate IncludesQueryBuilder
const includesQueryBuilder = new IncludesQueryBuilder().includes('lines')
console.log(includesQueryBuilder.build()) // "&include[]=lines"
try {
// Get invoices with included line items
const { data } = await client.invoices.list(accountId, [includesQueryBuilder])
console.log('Invoices: ', data)
} catch ({ statusCode, message }) {
// Handle error if API call failed
console.error(`Error fetching user: ${statusCode} - ${message}`)
}
数据字段注释
日期和时间
由于历史原因,FreshBooks API中的许多资源(大多为会计重述)返回日期/时间
"美国/东部"时区. 已作出一定努力,将这些模型转换为返回 Date 已正常化为世界协调时的对象.
货币价值
FreshBooks API 作为包含金额和货币代码的货币对象返回大多数货币值:
export default interface Money {
amount?: string
code?: string
}
该量作为字符串返回并存储,以防止浮点精度问题. 如果你这样做 计算这些值时,建议使用一个库进行小数计算,例如: 小数点.js, (中文(简体) ), 大块. js, (中文(简体) ), 或者说 大数.js