Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
manomintis authored and manomintis committed Feb 21, 2024
0 parents commit 6691945
Show file tree
Hide file tree
Showing 20 changed files with 578 additions and 0 deletions.
22 changes: 22 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# http://editorconfig.org

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.json]
insert_final_newline = ignore

[**.min.js]
indent_style = ignore
insert_final_newline = ignore

[MakeFile]
indent_style = space

[*.md]
trim_trailing_whitespace = false
26 changes: 26 additions & 0 deletions .github/lock.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
ignoreUnless: {{ STALE_BOT }}
---
# Configuration for Lock Threads - https://github.com/dessant/lock-threads-app

# Number of days of inactivity before a closed issue or pull request is locked
daysUntilLock: 60

# Skip issues and pull requests created before a given timestamp. Timestamp must
# follow ISO 8601 (`YYYY-MM-DD`). Set to `false` to disable
skipCreatedBefore: false

# Issues and pull requests with these labels will be ignored. Set to `[]` to disable
exemptLabels: ['Type: Security']

# Label to add before locking, such as `outdated`. Set to `false` to disable
lockLabel: false

# Comment to post before locking. Set to `false` to disable
lockComment: >
This thread has been automatically locked since there has not been
any recent activity after it was closed. Please open a new issue for
related bugs.
# Assign `resolved` as the reason for locking. Set to `false` to disable
setLockReason: false
24 changes: 24 additions & 0 deletions .github/stale.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
ignoreUnless: {{ STALE_BOT }}
---
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 60

# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7

# Issues with these labels will never be considered stale
exemptLabels:
- 'Type: Security'

# Label to use when marking an issue as stale
staleLabel: 'Status: Abandoned'

# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false
60 changes: 60 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
name: test

on:
- push
- pull_request

jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install
run: npm install
- name: Run lint
run: npm run lint

typecheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install
run: npm install
- name: Run typecheck
run: npm run typecheck

tests:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
node-version:
- 20.10.0
- 21.x
steps:
- uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Install
run: npm install
- name: Run tests
run: npm test
windows:
runs-on: windows-latest
strategy:
matrix:
node-version:
- 20.10.0
- 21.x
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Install
run: npm install
- name: Run tests
run: npm test
14 changes: 14 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
node_modules
coverage
.DS_STORE
.nyc_output
.idea
.vscode/
*.sublime-project
*.sublime-workspace
*.log
build
dist
yarn.lock
shrinkwrap.yaml
package-lock.json
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
4 changes: 4 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
build
docs
coverage
*.html
9 changes: 9 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# The MIT License

Copyright (c) 2023

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
96 changes: 96 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# AdonisJS API resources

Provides a transformation layer between models and actual API endpont responses in JSON format.

## Setup

Install the package:

```sh
npm install adonis-api-resources
```


Configure the package:

```sh
node ace configure adonis-api-resources
```


## Usage


Generate a new resource:

```sh
node ace make:resource UserResource
```


Edit newly generated app/resources/users_resource.ts to create output you need. This example shows how you may output user's full name even if your implementation of user model has separate fields for the first and last names:

```typescript
...
return {
full_name: data.firstName + ' ' + data.lastName,
}
...
```


Import your generated resource before using it, i.e. in a controller:

```typescript
import UsersResource from '#resources/users_resource'
```


Remove old endpoint return declaration:

```typescript
return user
```


Use the your generated resource instead:

```typescript
return new UsersResource(user).refine()
```


You may also use arrays of models, with resources:

```typescript
return new UsersResource(users).refine()
```

That's it. Enjoy yourself!


## Expected output examples


Model:

```json
{
"full_name": "John Doe"
}
```


Array of models:

```json
[
{
"full_name": "John Doe"
},
{
"full_name": "Jane Doe"
}
]
```

11 changes: 11 additions & 0 deletions bin/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { assert } from '@japa/assert'
import { configure, processCLIArgs, run } from '@japa/runner'

processCLIArgs(process.argv.splice(2))

configure({
files: ['tests/**/*.spec.ts'],
plugins: [assert()],
})

run()
28 changes: 28 additions & 0 deletions commands/make_resource.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* adonis-api-resources
*
* (c) Boris Abramov <boris@ideainc.eu>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

import { BaseCommand, args } from '@adonisjs/core/ace'
import { stubsRoot } from '../stubs/main.js'

export default class MakeResource extends BaseCommand {
static commandName = 'make:resource'
static description = 'Create a new API resource class'

@args.string({
description: 'The name of the resource',
})
declare name: string

async run(): Promise<void> {
const codemods = await this.createCodemods()
await codemods.makeUsingStub(stubsRoot, 'main.stub', {
entity: this.app.generators.createEntity(this.name),
})
}
}
81 changes: 81 additions & 0 deletions configure.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* adonis-api-resources
*
* (c) Boris Abramov <boris@ideainc.eu>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

import ConfigureCommand from '@adonisjs/core/commands/configure'
import fs from 'node:fs'

export async function configure(_command: ConfigureCommand) {
const codemods = await _command.createCodemods()

// Create "make" command
try {
await codemods.updateRcFile((rcFile) => {
rcFile.addCommand('adonis-api-resources/commands')
})
} catch (error) {
console.error('Unable to update adonisrc.ts file')
console.error(error)
}

/**
* Update JSON configuration files to create "resources" namespace
* @param {string} configName - Either "package.json" or "tsconfig.json"
* @returns {void} - No output
*/
function updateConfig(configName: 'package.json' | 'tsconfig.json'): void {
const generalErrorText = 'Failed to create #resources namespace'
const alreadyErrorText = 'Namespace #resources already exists in '
fs.readFile('./' + configName, 'utf-8', (err, jsonData) => {
if (err) {
console.log(generalErrorText, err)
} else {
try {
let data = JSON.parse(
// Prevent parsing failure by removing JSON invalid trailing commas, often present in tsconfig.json
jsonData.replace(/(?<=(true|false|null|["\d}\]])\s*),(?=\s*[}\]])/g, '')
)
switch (configName) {
case 'package.json':
if (data.imports?.['#resources/*'] !== undefined) {
console.log(alreadyErrorText + configName)
} else {
data['imports']['#resources/*'] = './app/resources/*.js'
}
break
case 'tsconfig.json':
if (data.compilerOptions?.paths?.['#resources/*'] !== undefined) {
console.log(alreadyErrorText + configName)
} else {
data['compilerOptions']['paths']['#resources/*'] = ['./app/resources/*.js']
}
break
}
// Output is altered to keep tsconfig.json syntax compact as it out of the box
fs.writeFile(
'./' + configName,
JSON.stringify(data, null, 2)
.replace(/(\[\n\ +\")/gm, '["')
.replace(/(\"\n\ +\])/gm, '"]'),
(error) => {
if (error) {
console.log(generalErrorText, error)
}
}
)
} catch (error) {
console.log(generalErrorText, error)
}
}
})
}

// Create "resources" namespace
updateConfig('package.json')
updateConfig('tsconfig.json')
}
11 changes: 11 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
* adonis-api-resources
*
* (c) Boris Abramov <boris@ideainc.eu>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

export { configure } from './configure.js'
export { Resource } from './src/resource.js'

0 comments on commit 6691945

Please sign in to comment.