insomnia/packages/insomnia-app/app/models/o-auth-2-token.js

82 lines
1.7 KiB
JavaScript
Raw Normal View History

2017-07-19 04:48:28 +00:00
// @flow
2018-06-25 17:42:50 +00:00
import type { BaseModel } from './index';
2017-07-19 04:48:28 +00:00
import * as db from '../common/database';
2017-07-19 04:48:28 +00:00
type BaseOAuth2Token = {
refreshToken: string,
accessToken: string,
expiresAt: number | null, // Should be Date.now() if valid
// Debug
xResponseId: string | null,
xError: string | null,
2017-07-19 04:48:28 +00:00
// Error handling
error: string,
errorDescription: string,
errorUri: string,
2017-07-19 04:48:28 +00:00
};
export type OAuth2Token = BaseModel & BaseOAuth2Token;
export const name = 'OAuth 2.0 Token';
export const type = 'OAuth2Token';
export const prefix = 'oa2';
export const canDuplicate = false;
2018-06-25 17:42:50 +00:00
export function init(): BaseOAuth2Token {
return {
2017-07-19 04:48:28 +00:00
refreshToken: '',
accessToken: '',
expiresAt: null, // Should be Date.now() if valid
// Debug
xResponseId: null,
xError: null,
// Error handling
2017-07-19 04:48:28 +00:00
error: '',
errorDescription: '',
errorUri: '',
};
}
2018-06-25 17:42:50 +00:00
export function migrate<T>(doc: T): T {
return doc;
}
2018-06-25 17:42:50 +00:00
export function create(patch: Object = {}): Promise<OAuth2Token> {
if (!patch.parentId) {
2018-10-17 16:42:33 +00:00
throw new Error(`New OAuth2Token missing \`parentId\` ${JSON.stringify(patch)}`);
}
return db.docCreate(type, patch);
}
2018-10-17 16:42:33 +00:00
export function update(token: OAuth2Token, patch: Object): Promise<OAuth2Token> {
return db.docUpdate(token, patch);
}
2018-06-25 17:42:50 +00:00
export function remove(token: OAuth2Token): Promise<void> {
return db.remove(token);
}
2018-06-25 17:42:50 +00:00
export function getByParentId(parentId: string): Promise<OAuth2Token | null> {
return db.getWhere(type, { parentId });
}
2018-10-17 16:42:33 +00:00
export async function getOrCreateByParentId(parentId: string): Promise<OAuth2Token> {
2018-06-25 17:42:50 +00:00
let token = await db.getWhere(type, { parentId });
if (!token) {
2018-06-25 17:42:50 +00:00
token = await create({ parentId });
}
return token;
}
2018-06-25 17:42:50 +00:00
export function all(): Promise<Array<OAuth2Token>> {
return db.all(type);
}