Skip to content

Commit

Permalink
update signalSSample
Browse files Browse the repository at this point in the history
  • Loading branch information
SanderElias committed Jul 13, 2024
1 parent b07455e commit 4541ff8
Show file tree
Hide file tree
Showing 7 changed files with 41 additions and 18 deletions.
6 changes: 6 additions & 0 deletions projects/api-boundries/src/app/relations.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ const randChar = () => seed[randomInt(seed.length)];
const randChars = (n = 3) => Array.from({ length: n }, () => randChar()).join('');

export const getId = () => randChars(4) + '-' + Math.round(performance.now() * 10000000000).toString(36);
export const createUniqueId = Date.now()
.toString(36)
.split('')
.reverse()
.map(c => c + randChar())
.join();

@Injectable({
providedIn: 'root',
Expand Down
13 changes: 5 additions & 8 deletions src/app/demo-users.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Injectable } from '@angular/core';
import { first, map, mergeMap, shareReplay, startWith, Subject, take, tap, timer, firstValueFrom } from 'rxjs';
import { createUniqueId } from './util/random-things';

const chanceProm = import('chance')
/** some trickery as the typings apparently don't match the reality */
Expand All @@ -15,7 +16,7 @@ enum UserState {
}

export interface DemoUser {
id: number;
id: string;
username: string;
password?: string;
email: string;
Expand Down Expand Up @@ -61,7 +62,7 @@ export class DemoUserService {
// users.reduce((min, line) => (min = Math.max(min, line.id)), 0) + 1;
const newUsers = await Promise.all(
Array.from({ length: newUserCount }).map(async (e, i) => ({
id: base + i,
id: createUniqueId(),
...(await fakeUser()),
}))
);
Expand All @@ -72,18 +73,14 @@ export class DemoUserService {
/** async helper to 'save' users. async makes it easier to read if we wait on the suer promise */
async saveUser(user: DemoUser) {
/** get a current list of users out of the 'cache'*/
const users = await this.allUsers$.pipe(take(1)).toPromise();
const users = await firstValueFrom(this.allUsers$);
const index = users.findIndex(row => row.id === user.id);
if (index > -1) {
/** update the found user */
Object.assign(users[index], user);
} else {
// create a new id
let id;
while (!id || users.findIndex(row => row.id === id) > -1) {
/** create an random id and check if its used */
id = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
}
let id = createUniqueId();
/** add it to th array of users. */

users.unshift({ ...user, id });
Expand Down
4 changes: 2 additions & 2 deletions src/app/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,6 @@ export const routes: Routes = [
path: 'signalPlay/:id',
loadComponent: () => import('./signal-play/signal-play.component'),
},
{ path: '**', redirectTo: 'routeList' },
// { path: '**', redirectTo: 'signalPlay' },
// { path: '**', redirectTo: 'routeList' },
{ path: '**', redirectTo: 'signalPlay' },
];
14 changes: 11 additions & 3 deletions src/app/signal-play/signal-play.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { JsonPipe } from '@angular/common';
standalone: true,
imports: [JsonPipe],
template: `
<h3>{{ sps.$lastId() }}</h3>
<h3>{{ $availableUserCount() }}</h3>
<hr />
<pre><code>{{$user()|json}}</code></pre>
<hr />
Expand All @@ -18,9 +18,17 @@ import { JsonPipe } from '@angular/common';
})
export default class SignalPlayComponent {
sps = inject(SignalPlayService);
id = model<number>(0);
id = model<string>('');

$user = computed(() => {
const user = this.sps.getUser(this.id());
if (user) return user;
// none found, get first one!
return this.sps.$users()[0];
});

$availableUserCount = computed(() => this.sps.$users().length);

$user = computed(() => this.sps.getUser(this.id()));
relId = (n = 1) => {
const newId = this.sps.getRelative(this.id(), n);
return newId ? newId : this.id();
Expand Down
8 changes: 4 additions & 4 deletions src/app/signal-play/signal-play.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ export class SignalPlayService {

$users = observableComputed(() => this.users.allUsers$);

getUser = (n: number) => {
getUser = (n: string) => {
const users = this.$users();
return users?.find(user => +user.id === +n);
return users?.find(user => user.id === n);
};

getRelative = (id: number, offset = 1) => {
getRelative = (id: string, offset = 1) => {
const users = this.$users() || [];
const userIndex = users.findIndex(u => +u.id === +id);
const userIndex = users.findIndex(u => u.id === id);
if (userIndex === -1) {
return users[0]?.id; // not found, return first id
}
Expand Down
12 changes: 12 additions & 0 deletions src/app/util/random-things.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const seed = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
export const randomInt = (max = 2000) => Math.floor(Math.random() * max);
const randChar = () => seed[randomInt(seed.length)];
const randChars = (n = 3) => Array.from({ length: n }, () => randChar()).join('');

export const getId = () => randChars(4) + '-' + Math.round(performance.now() * 10000000000).toString(36);
export const createUniqueId = () => Date.now()
.toString(36)
.split('')
.reverse()
.map(c => c + randChar())
.join('');
2 changes: 1 addition & 1 deletion src/utils/signal-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type ToWritableSignal = {
/**
* Convert an observable into a writable signal.
* @param src the observable. Will only take the first submitted value.
* @param options, takes an optional initial value and an optional error callback.
* @param options, takes an optional initial value and an optional error callback.O
* @returns a writeable signal that will be updated with the first value from the observable.
*/
export const toWritableSignal = <T, U>(
Expand Down

0 comments on commit 4541ff8

Please sign in to comment.