Skip to content

Commit

Permalink
feat: add blocks publish --all command (#466)
Browse files Browse the repository at this point in the history
* feat: add blocks publish --all command

* feat: add blocks release command

---------

Co-authored-by: Thomas Timmer <[email protected]>
  • Loading branch information
thomas9911 and Thomas Timmer authored Aug 23, 2024
1 parent f2de167 commit b800eac
Show file tree
Hide file tree
Showing 5 changed files with 163 additions and 13 deletions.
29 changes: 19 additions & 10 deletions src/bb-blocks-publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
validateBlock,
} from './validations/function-block-validations';

program.name('bb blocks publish').parse(process.argv);
program.option('--all').name('bb blocks publish').parse(process.argv);

const workingDir = process.cwd();
const baseBlocksPath = path.join(workingDir, 'blocks');
Expand Down Expand Up @@ -79,15 +79,24 @@ void (async (): Promise<void> => {
title: path.basename(block, '.json'),
value: block,
}));
const { selected } = (await prompts([
{
type: 'multiselect',
name: 'selected',
message: 'Which blocks do you want to publish?',
choices,
instructions: false,
},
])) as { selected: string[] };
const { all } = program.opts();

let selected: string[] = [];

if (all) {
selected = blocks;
} else {
const results = (await prompts([
{
type: 'multiselect',
name: 'selected',
message: 'Which blocks do you want to publish?',
choices,
instructions: false,
},
])) as { selected: string[] };
selected = results.selected;
}

selected.forEach((jsonFile) => {
// eslint-disable-next-line no-void
Expand Down
24 changes: 24 additions & 0 deletions src/bb-blocks-release.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import program from 'commander';
import releaseBlocks from './blocks/releaseBlocks';

program
.usage('[options] [blockIds...]')
.option(
'-a, --all',
'release all dev blocks that are attached to your account',
)
.name('bb blocks release')
.parse(process.argv);

const { all }: { all?: boolean } = program.opts();
const blockIds = program.args;

if (!all && !blockIds.length) {
console.error('No block IDs provided');
process.exit(1);
}

// eslint-disable-next-line no-void
void (async (): Promise<void> => {
await releaseBlocks({ all, blockIds });
})();
5 changes: 3 additions & 2 deletions src/bb-blocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import program from 'commander';

/* internal dependencies */

import { CommandBlocks } from './types';
import type { CommandBlocks } from './types';

/* setup */

const availableCommands: CommandBlocks[] = ['publish', 'new'];
const availableCommands: CommandBlocks[] = ['publish', 'release', 'new'];

/* process arguments */

Expand All @@ -17,6 +17,7 @@ program
.name('bb blocks')
.command('new [blocks-name]', 'Initialize a new block')
.command('publish', 'publish blocks of current working directory')
.command('release', 'release dev blocks')
.on('command:*', ([command]: string[]): void => {
if (!availableCommands.includes(command as CommandBlocks)) {
console.error('Invalid command: %s\n', command);
Expand Down
116 changes: 116 additions & 0 deletions src/blocks/releaseBlocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import fetch from 'node-fetch';
import type { Response, RequestInit } from 'node-fetch';
import Config from '../functions/config';
import FusionAuth from '../utils/login';

const GET_DEV_BLOCKS = '/blocks/my-dev-blocks';
const POST_RELEASE_BLOCKS = '/blocks/release';

const sendBlockstoreRequest = async (
urlPath: string,
method: string,
body: RequestInit['body'],
config: Config,
fusionAuth: FusionAuth,
applicationId: string,
): Promise<Response> => {
const url = `${config.blockstoreApiUrl}${urlPath}`;
return fetch(url, {
agent: config.agent,
method,
body,
headers: {
'content-type': 'application/json',
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
Authorization: `Bearer ${fusionAuth.jwt()}`,
ApplicationId: applicationId,
Accept: 'application/json',
},
}).then(async (res) => {
if (res.status === 401 || res.status === 403) {
await fusionAuth.ensureLogin();
return sendBlockstoreRequest(
urlPath,
method,
body,
config,
fusionAuth,
applicationId,
);
}

return res;
});
};

const fetchAllDevBlocks = async (
config: Config,
fusionAuth: FusionAuth,
applicationId: string,
): Promise<Response> => {
return sendBlockstoreRequest(
GET_DEV_BLOCKS,
'GET',
undefined,
config,
fusionAuth,
applicationId,
);
};

const releaseBlocksInBlockstore = async (
blockIds: string[],
config: Config,
fusionAuth: FusionAuth,
applicationId: string,
): Promise<boolean> => {
const response = await sendBlockstoreRequest(
POST_RELEASE_BLOCKS,
'POST',
JSON.stringify({ block_ids: blockIds }),
config,
fusionAuth,
applicationId,
);
if (!response.ok) {
await response
.text()
.then((text) =>
console.error(`Failed to release blocks in Blockstore: ${text}`),
);
return false;
}
return true;
};

const releaseBlocks = async ({
all,
blockIds,
}: {
all?: boolean;
blockIds: string[];
}): Promise<boolean> => {
const config = new Config();
const fusionAuth = new FusionAuth(config);
const applicationId = await config.applicationId();
if (!applicationId) {
throw new Error(
"Couldn't publish block(s), Error: application id not found",
);
}

let blockIdsToBeReleased: string[] = blockIds;
if (all) {
const res = await fetchAllDevBlocks(config, fusionAuth, applicationId);
blockIdsToBeReleased = (await res.json()) as string[];
}

return releaseBlocksInBlockstore(
blockIdsToBeReleased,
config,
fusionAuth,
applicationId,
);
};

export default releaseBlocks;
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export type CommandFunctions =
| 'bump'
| 'test';

export type CommandBlocks = 'publish' | 'new';
export type CommandBlocks = 'publish' | 'release' | 'new';

export type CommandInteractions = 'generate';

Expand Down

0 comments on commit b800eac

Please sign in to comment.