Skip to content

Commit

Permalink
feat: api client logic
Browse files Browse the repository at this point in the history
  • Loading branch information
alvarosabu committed Sep 18, 2024
1 parent c345646 commit 5854401
Show file tree
Hide file tree
Showing 9 changed files with 169 additions and 7 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"test": "vitest"

},
"dependencies": {
"chalk": "^5.3.0",
"commander": "^12.1.0",
"consola": "^3.2.3",
"inquirer": "^10.2.2"
"inquirer": "^10.2.2",
"storyblok-js-client": "^6.9.2"
},
"devDependencies": {
"@storyblok/eslint-config": "^0.2.0",
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

52 changes: 52 additions & 0 deletions src/api.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { apiClient } from './api'
import StoryblokClient from 'storyblok-js-client';

// Mock the StoryblokClient to prevent actual HTTP requests
vi.mock('storyblok-js-client', () => {
const StoryblokClientMock = vi.fn().mockImplementation((config) => {
return {
config,
};
});

return {
default: StoryblokClientMock,
__esModule: true, // Important for ESM modules
};
});

describe('Storyblok API Client', () => {
beforeEach(() => {
// Reset the module state before each test to ensure test isolation
vi.resetModules();
});

it('should have a default region of "eu"', () => {
const { region } = apiClient()
expect(region).toBe('eu')
})

it('should return the same client instance when called multiple times without changes', () => {
const api1 = apiClient();
const client1 = api1.client;

const api2 = apiClient();
const client2 = api2.client;

expect(client1).toBe(client2);
});

it('should set the region on the client', () => {
const { setRegion } = apiClient();
setRegion('us');
const { region } = apiClient();
expect(region).toBe('us');
})

it('should set the access token on the client', () => {
const { setAccessToken } = apiClient();
setAccessToken('test-token');
const { client } = apiClient();
expect(client.config.accessToken).toBe('test-token');
})
})
46 changes: 46 additions & 0 deletions src/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import StoryblokClient from "storyblok-js-client";
import { regions } from "./constants";

export interface ApiClientState {
region: string,
accessToken: string,
client: StoryblokClient | null
}

const state: ApiClientState = {
region: 'eu',
accessToken: '',
client: null
}

export function apiClient() {
if (!state.client) {
createClient()
}

function createClient() {
state.client = new StoryblokClient({
accessToken: state.accessToken,
region: state.region
})
}

function setAccessToken(accessToken: string) {
state.accessToken = accessToken
state.client = null
createClient()
}

function setRegion(region: string) {
state.region = region
state.client = null
createClient()
}

return {
region: state.region,
client: state.client,
setAccessToken,
setRegion,
}
}
9 changes: 8 additions & 1 deletion src/commands/login/actions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
export const login = () => {


export const loginWithToken = () => {
// eslint-disable-next-line no-console
console.log('Login')
}

export const loginWithEmailAndPassword = () => {

}

44 changes: 40 additions & 4 deletions src/commands/login/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,53 @@
import chalk from 'chalk'
import { commands } from '../../constants'
import { commands, regions } from '../../constants'
import { getProgram } from '../../program'
import { formatHeader, handleError } from '../../utils'
import { loginWithToken } from './actions'
import inquirer from 'inquirer'

const program = getProgram() // Get the shared singleton instance

const allRegionsText = Object.values(regions).join(", ");
const loginStrategy = [
{
type: 'list',
name: 'strategy',
message: 'How would you like to login?',
choices: [
{
name: 'With email',
value: 'login-with-email',
short: 'Email'
},
{
name: 'With Token (SSO)',
value: 'login-with-token',
short: 'Token'
}
]
}
]
export const loginCommand = program
.command(commands.LOGIN)
.description('Login to the Storyblok CLI')
.action(async () => {
try {
.option("-t, --token <token>", "Token to login directly without questions, like for CI environments")
.option(
"-r, --region <region>",
`The region you would like to work in. Please keep in mind that the region must match the region of your space. This region flag will be used for the other cli's commands. You can use the values: ${allRegionsText}.`,
regions.EU
)
.option("-ci", '--ci', false)
.action(async (options) => {
if(options.token || options.Ci) {
console.log('CI version')
} else {
console.log(formatHeader(chalk.bgHex('#8556D3').bold.white(` ${commands.LOGIN} `)))
/* login() */

const { strategy } = await inquirer.prompt(loginStrategy)

Check failure on line 46 in src/commands/login/index.ts

View workflow job for this annotation

GitHub Actions / build (20)

No overload matches this call.
console.log(strategy)
}
try {
loginWithToken()
}
catch (error) {
handleError(error as Error)
Expand Down
11 changes: 11 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
export const commands = {
LOGIN: 'login',
}

export const regions = {
EU: 'eu',
US: 'us',
CN: 'cn'
}

export const DEFAULT_AGENT = {
SB_Agent: 'SB-CLI',
SB_Agent_Version: process.env.npm_package_version || '4.x'
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const messageText = ` Starting Blok machine... `
console.log(formatHeader(`
${introText} ${messageText}`))

program.option("-s, --space [value]", "space ID");

program.on('command:*', () => {
console.error(`Invalid command: ${program.args.join(' ')}`)
Expand Down
1 change: 1 addition & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { defineConfig } from 'vite'

export default defineConfig({
test: {
globals: true
// ... Specify options here.
},
})

0 comments on commit 5854401

Please sign in to comment.