insomnia/packages/insomnia-app/app/models/environment.js

81 lines
1.9 KiB
JavaScript
Raw Normal View History

// @flow
2016-11-10 05:56:23 +00:00
import * as db from '../common/database';
2018-06-25 17:42:50 +00:00
import type { BaseModel } from './index';
import type { Workspace } from './workspace';
2016-09-21 20:32:45 +00:00
export const name = 'Environment';
export const type = 'Environment';
export const prefix = 'env';
export const canDuplicate = true;
type BaseEnvironment = {
name: string,
data: Object,
color: string | null,
2018-06-07 17:55:28 +00:00
metaSortKey: number,
// For sync control
isPrivate: boolean,
};
export type Environment = BaseModel & BaseEnvironment;
2018-06-25 17:42:50 +00:00
export function init() {
2016-11-10 01:15:27 +00:00
return {
name: 'New Environment',
data: {},
color: null,
2018-06-07 17:55:28 +00:00
isPrivate: false,
metaSortKey: Date.now(),
};
}
2018-06-25 17:42:50 +00:00
export function migrate(doc: Environment): Environment {
return doc;
}
2018-06-25 17:42:50 +00:00
export function create(patch: Object = {}): Promise<Environment> {
2016-09-21 20:32:45 +00:00
if (!patch.parentId) {
2018-10-17 16:42:33 +00:00
throw new Error(`New Environment missing \`parentId\`: ${JSON.stringify(patch)}`);
2016-09-21 20:32:45 +00:00
}
return db.docCreate(type, patch);
}
2016-09-21 20:32:45 +00:00
2018-10-17 16:42:33 +00:00
export function update(environment: Environment, patch: Object): Promise<Environment> {
2016-09-21 20:32:45 +00:00
return db.docUpdate(environment, patch);
}
2016-09-21 20:32:45 +00:00
2018-06-25 17:42:50 +00:00
export function findByParentId(parentId: string): Promise<Array<Environment>> {
return db.find(type, { parentId }, { metaSortKey: 1 });
}
2016-09-21 20:32:45 +00:00
2018-10-17 16:42:33 +00:00
export async function getOrCreateForWorkspaceId(workspaceId: string): Promise<Environment> {
2018-06-25 17:42:50 +00:00
const environments = await db.find(type, { parentId: workspaceId });
2017-11-13 19:05:46 +00:00
if (!environments.length) {
return create({
2017-09-13 06:11:49 +00:00
parentId: workspaceId,
name: 'Base Environment',
});
}
2017-11-13 19:05:46 +00:00
return environments[environments.length - 1];
}
2018-10-17 16:42:33 +00:00
export async function getOrCreateForWorkspace(workspace: Workspace): Promise<Environment> {
2017-09-13 06:11:49 +00:00
return getOrCreateForWorkspaceId(workspace._id);
}
2018-06-25 17:42:50 +00:00
export function getById(id: string): Promise<Environment | null> {
return db.get(type, id);
}
2018-06-25 17:42:50 +00:00
export function remove(environment: Environment): Promise<void> {
2016-09-21 20:32:45 +00:00
return db.remove(environment);
}
2016-09-21 20:32:45 +00:00
2018-06-25 17:42:50 +00:00
export function all(): Promise<Array<Environment>> {
return db.all(type);
}